LeetCode Set Matrix Zeroes

来源:互联网 发布:阿里云cdn加速设置 编辑:程序博客网 时间:2024/06/10 08:13

不让用空间很操蛋,其实就是用别的数(不在整数的表示范围内,程序中用INT_MAX都不行,只能UINT_MAX)作为标记,如果能考虑到迭代一次后的数组会影响结果这题就解决了一半,接下来的思路是分别遍历,先横着遍历,找零的,但是不能把行列改变为0因为会影响下一次遍历,所以要一个标记的数UINT_MAX(开辟空间也是解决这),然后竖着遍历,这次可以改行列的值了同时记得把原来的UINT_MAX改成0。就这样了。这题没怎么想,一不小心瞥了一眼答案,O(∩_∩)O~

// LeetCode_SetMatrixZeroes.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <vector>using namespace std;void setZeroes(vector<vector<int> > &matrix) {int lenRow = matrix.size();int lenColumn = 0;if (lenRow!=0){lenColumn = matrix[0].size();}for (int i=0;i<lenRow;i++){for(int j=0;j<lenColumn;j++){if (matrix[i][j]==0){for (int k=0;k<lenColumn;k++){if(matrix[i][k]!=0)matrix[i][k] = UINT_MAX;//INT_MAX}break;}}}for(int j=0;j<lenColumn;j++){for (int i=0;i<lenRow;i++){if (matrix[i][j]==0){for (int k=0;k<lenRow;k++){matrix[k][j] = 0;}break;}if (matrix[i][j]==UINT_MAX){matrix[i][j]=0;}}}}int _tmain(int argc, _TCHAR* argv[]){vector<vector<int> > matrix;vector<int> temp;temp.clear();temp.push_back(1);temp.push_back(0);temp.push_back(2);temp.push_back(3);matrix.push_back(temp);temp.clear();temp.push_back(1);temp.push_back(4);temp.push_back(5);temp.push_back(6);matrix.push_back(temp);temp.clear();temp.push_back(1);temp.push_back(8);temp.push_back(2);temp.push_back(0);matrix.push_back(temp);int lenRow = matrix.size();int lenColumn = 0;if (lenRow!=0){lenColumn = matrix[0].size();}for (int i=0;i<lenRow;i++){for(int j=0;j<lenColumn;j++){cout<<matrix[i][j]<<" ";}cout<<endl;}setZeroes(matrix);cout<<" after setzero"<<endl;for (int i=0;i<lenRow;i++){for(int j=0;j<lenColumn;j++){cout<<matrix[i][j]<<" ";}cout<<endl;}system("pause");return 0;}


0 0
原创粉丝点击