一、Search a 2D Matrixspa
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 bool res = false; 5 int row = -1; 6 for(int i=1; i<matrix.size(); ++i) 7 { 8 if(target>=matrix[i-1][0] &&target<matrix[i][0]) 9 { 10 row = i-1; 11 break; 12 } 13 } 14 if(row == -1) 15 row = matrix.size()-1; 16 17 for(int j=0; j<matrix[row].size(); ++j) 18 if(target == matrix[row][j]) 19 return true; 20 21 return false; 22 } 23 };
二、Search a 2D Matrix IIcode
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 if(matrix.empty() || target<matrix[0][0] ) 5 return false; 6 int row = matrix.size(), col = matrix[0].size(); 7 int i=row-1, j=0; 8 while(i>=0 && j<col) 9 { 10 if(matrix[i][j]==target) 11 return true; 12 else if(matrix[i][j]<target) 13 j++; 14 else if(matrix[i][j]>target) 15 i--; 16 } 17 return false; 18 } 19 };