73. Set Matrix Zeroes
分析:如果没有空间限制,这道题就很简单,但是要求空间复杂度为O(1),因此需要一些技巧。代码如下(copy网上的代码)
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { bool bColZero = false, bRowZero = false; if (matrix.size() == 0 || matrix[0].size() == 0) { return; } // Mark bColZero true when col[0] contains zero. for (size_t row = 0; row < matrix.size(); ++row) { if (!matrix[row][0]) bColZero = true; } // Mark bRowZero true when row[0] contains zero. for (size_t col = 0; col < matrix[0].size(); ++col) { if (!matrix[0][col]) bRowZero = true; } // Map zero points to row[0] and col[0]. for (size_t row = 1; row < matrix.size(); ++row) { for (size_t col = 1; col < matrix[row].size(); ++col) { if (!matrix[row][col]) { matrix[0][col] = 0; matrix[row][0] = 0; } } } // Set zero according to row[0] and col[0]. for (size_t row = 1; row < matrix.size(); ++row) { for (size_t col = 1; col < matrix[row].size(); ++col) { if (!matrix[row][0] || !matrix[0][col]) { matrix[row][col] = 0; } } } // Process col[0]. if (bColZero) { for (size_t row = 0; row < matrix.size(); ++row) { matrix[row][0] = 0; } } // Process row[0]. if (bRowZero) { for (size_t col = 0; col < matrix[0].size(); ++col) { matrix[0][col] = 0; } } } };
------------------------------------------------------------------------------分割线-------------------------------------------------------------------
74. Search a 2D Matrix
题目
分析,这道题目在《剑指offer》上出现过,思想是分段查找,只是查找的起点是右上角的元素,代码如下:
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int i = 0, j = matrix[0].size() - 1; 7 8 while (i < matrix.size() && j >= 0) 9 { 10 if (target == matrix[i][j]) 11 return true; 12 else if (target < matrix[i][j]) 13 j--; 14 else 15 i++; 16 } 17 18 return false; 19 } 20 };
--------------------------------------------------------------------分割线------------------------------------------------------------------------------
75. Sort Colors
题目
分析:简单题目,可以直接统计0,1,2的个数,然后赋值即可
代码如下:
class Solution { public: void sortColors(vector<int>& nums) { int size = nums.size(); int zero=0,one=0,two = 0; int i,j; for(i=0;i<size;i++) { if(0 == nums[i]) zero++; else if(1 == nums[i]) one++; else two++; } i=0; j=0; for(j=0;j<zero;j++) nums[i++]=0; for(j=0;j<one;j++) nums[i++]=1; for(j=0;j<two;j++) nums[i++]=2; } };
时间: 2024-10-29 19:10:39