leetcode刷题,总结,记录,备忘 73

leetcode73Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

Follow up:

Did you use extra space?
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?

如果没按最高要求的话,,其实还是比较简单的,先遍历,然后把列上出现0的列号存入set,然后再次遍历,同行有0就全部置为0,否则遍历set,将相应的列上置为0。更优解法待我有空研究。
class Solution {
public:
     void setZeroes(vector<vector<int>>& matrix) {
        set<int> temp;
        int i = 0;
        
        for (; i != matrix.size(); ++i)
        {
            vector<int>::iterator it = matrix[i].begin();
            
            while ((it = find(it, matrix[i].end(), 0)) != matrix[i].end())
            {
                temp.insert(it - matrix[i].begin());
                it++;
            }
        }
        
        for (i = 0; i != matrix.size(); ++i)
        {
            if (find(matrix[i].begin(), matrix[i].end(), 0) != matrix[i].end())
            fill(matrix[i].begin(), matrix[i].end(), 0);
            else
            {
                for (set<int>::iterator it = temp.begin(); it != temp.end(); ++it)
                {
                    matrix[i][*it] = 0;
                }
            }
        }
    }
};

你可能感兴趣的:(leetcode刷题,总结,记录,备忘 73)