设置矩阵zreos:free():无效的下一个大小(快速):0x00000000029c21d0

时间:2018-12-08 10:46:07

标签: c++

问题:设置矩阵零(leetcode https://leetcode.com/problems/set-matrix-zeroes/submissions/中的一种做法)
给定一个m x n矩阵,如果元素为0,则将其整个行和列设置为0。就地进行设置。

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]
Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]
Follow up:

A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

提交代码时,出现错误enter image description here

我想知道为什么会出错吗? 这是我的代码:

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int i,j;
        int col_size = matrix[0].size();
        int *flag = new int [col_size + 1];
        for(i = 0; i < matrix.size();i++)
        {
            for(j = 0; j < matrix[i].size(); j++)
            {
                if(matrix[i][j] == 0)
                {
                    flag[i] = 1;
                    flag[col_size] = 1;
                }

            }
            if(flag[col_size] == 1)
            {
                for(j = 0; j < matrix[i].size(); j++)
                {
                    matrix[i][j] = 0;
                } 
                flag[col_size] = 0;
            }
        }
        for(j = 0; j < col_size; j++)
        {
            if(flag[j] == 1)
                for(i = 0; i < matrix.size(); i++)
                {
                    matrix[i][j] = 0;
                }
        }
        delete [] flag;
    }
};

谢谢!

2 个答案:

答案 0 :(得分:0)

您已分配了大小矩阵为[0] .size()的标志,即列数。
但是这里-​​

    flag[i] = 1;

i转到matrix.size()-1,即行数。
对于M x N矩阵,如果M> N(此处实际上为N + 1,因为您已为其他目的分配了额外的位置),则您的代码正在修改数组外部的位置。
在这里-

    delete [] flag;

您要删除的内存多于为M> N + 1分配的内存。

答案 1 :(得分:-1)

对不起!我没有认真检查我的代码。错误是gulp.task('js', (entry, outputFileName, jsOutputDir) => rollup({ input: entry, plugins: [ builtins(), nodeResolve({ browser: true }), babel({ exclude: 'node_modules/**' }), commonJs(), globals(), uglify(), json() ], format: 'umd' }) .on('error', function (err) { console.error(err) this.emit('end') }) // point to the entry file. .pipe(source(outputFileName)) // buffer the output. most gulp plugins, including gulp-sourcemaps, don't support streams. .pipe(buffer()) // tell gulp-sourcemaps to load the inline sourcemap produced by rollup-stream. .pipe(gulpSourceMaps.init({loadMaps: true})) // write the sourcemap alongside the output file. .pipe(gulpSourceMaps.write('.')) // Output file diretory .pipe(gulp.dest(jsOutputDir)) ) 应该是flag[i] = 1 enter image description here

现在,代码可以运行了。 enter image description here

感谢您的友好回答!