set-matrix-zeroes当元素为0则设矩阵内行与列均为0
生活随笔
收集整理的這篇文章主要介紹了
set-matrix-zeroes当元素为0则设矩阵内行与列均为0
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
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(m?n) 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,而后利用第一行和第一列保存狀態,最后根據開始的判斷決定是否將第一行和第一列置0
1 //時間復雜度O(mn),空間復雜度O(1) 2 //利用第一行和第一列的空間做記錄 3 class Solution { 4 public: 5 void setZeroes(vector<vector<int> > &matrix) { 6 const int row = matrix.size(); 7 const int col = matrix[0].size(); 8 bool row_flg = false, col_flg = false; 9 10 //判斷第一行和第一列是否有零,防止被覆蓋 11 for (int i = 0; i < row; i++) 12 if (0 == matrix[i][0]) { 13 col_flg = true; 14 break; 15 } 16 for (int i = 0; i < col; i++) 17 if (0 == matrix[0][i]) { 18 row_flg = true; 19 break; 20 } 21 //遍歷矩陣,用第一行和第一列記錄0的位置 22 for (int i = 1; i < row; i++) 23 for (int j = 1; j < col; j++) 24 if (0 == matrix[i][j]) { 25 matrix[i][0] = 0; 26 matrix[0][j] = 0; 27 } 28 //根據記錄清零 29 for (int i = 1; i < row; i++) 30 for (int j = 1; j < col; j++) 31 if (0 == matrix[i][0] || 0 == matrix[0][j]) 32 matrix[i][j] = 0; 33 //最后處理第一行 34 if (row_flg) 35 for (int i = 0; i < col; i++) 36 matrix[0][i] = 0; 37 if (col_flg) 38 for (int i = 0; i < row; i++) 39 matrix[i][0] = 0; 40 } 41 };?
轉載于:https://www.cnblogs.com/zl1991/p/9630343.html
總結
以上是生活随笔為你收集整理的set-matrix-zeroes当元素为0则设矩阵内行与列均为0的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【WPF】ListBox嵌套与事件冒泡
- 下一篇: linux查看系统的日志的一些实用操作