(leetcode)Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3, return true.
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 int rowsize = matrix.size();//1 5 int colsize = matrix[0].size();//2 6 if(rowsize == 0) return false; 7 if(colsize == 0) return false; 8 9 int i = 0, j = colsize-1; 10 while(i < rowsize && j >= 0) 11 { 12 if(target == matrix[i][j]) 13 return true; 14 else if(target > matrix[i][j]) 15 ++i; 16 else 17 --j; 18 } 19 return false; 20 } 21 };

浙公网安备 33010602011771号