1. 程式人生 > >LeetCode - 73. Set Matrix Zeroes

LeetCode - 73. Set 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.

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

               [1,0,1],                            [0,0,0],

               [1,1,1]   ]                         [1,0,1]   ]

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?

解:

    題目意思很簡單,就是對於一個矩陣,只要 i, j 位置為0,就將第 i 行,第 j 列都設為 0。

    題目的主要目的在於follow up中講到的,m * n 大小的空間複雜度是一個很差的方法(也就是弄一個新的一樣大的矩陣重新賦值),用 m + n 的空間複雜度也不是最好的solution,能不能有更好的方法。

    首先我是先實現了 O(m

 + n) space 的方法,也就是用兩個vector記錄哪些行要變為0,哪些列要變為0,然後修改矩陣即可。

void setZeroes(vector<vector<int>>& matrix)
{
    int rows = matrix.size(), cols = matrix[0].size();
    vector<int> zero_col, zero_row;
    
    // 必須遍歷所有位置
    for(int i = 0; i < rows; i++)
        for(int j = 0; j < cols; j++)
        {
            if(matrix[i][j] == 0)
            {
                zero_col.push_back(j);      // 第 j 列有 0
                zero_row.push_back(i);      // 第 i 行有 0
            }
        }
    for(int r : zero_row)
        for(int& m : matrix[r])
            m = 0;
    for(int c : zero_col)
        for(int i = 0; i < rows; i++)
            matrix[i][c] = 0;
}

    上述程式碼是可以AC的,不過只beat 22% 的cpp submission,且不是題目要求的最好的方法。

    對於這種矩陣我第一想法就是用負數表示要變成0的數,然後最後將所有負數變為0。AC程式碼如下:

void setZeroes(vector<vector<int>>& matrix)
{
    int rows = matrix.size(), cols = matrix[0].size();
    bool flag = false;
    
    // 必須遍歷所有位置
    for(int i = 0; i < rows; i++)
        for(int j = 0; j < cols; j++)
        {
            if(matrix[i][j] == 0)
            {
                flag = true;
                for(int t = 0; t < rows; t++)    // 這一列非0元素全設為-1, 不能修改0
                    if(matrix[t][j] != 0)
                        matrix[t][j] = -99999;
                for(int t = 0; t < cols; t++)    // 這一行非0元素全設為-1, 不能修改0
                    if(matrix[i][t] != 0)
                        matrix[i][t] = -99999;
            }
        }
    if(flag == false)
        return ;
    
    for(auto& r : matrix)
        for(auto& i : r)
            if(i == -99999)
                i = 0;   
}

    雖然過了,而且也沒有用多餘的空間,但是其實是有bug的,因為矩陣測試用例中是有負數的,只不過沒有-99999而已。