题目:
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 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int m = matrix.size(); 7 int n = matrix[0].size(); 8 if (matrix[0][0]>target || matrix[m-1][n-1]<target) return false; 9 int top = 0; 10 int down = m-1; 11 int mid; 12 while (top <= down) { 13 mid = (top+down)/2; 14 if (target == matrix[mid][0]) return true; 15 if (target > matrix[mid][0]) top = mid+1; 16 else down = mid-1; 17 } 18 int row = down; 19 int left = 0; 20 int right = n-1; 21 while (left <= right) { 22 mid = (left+right)/2; 23 if (target == matrix[row][mid]) return true; 24 if (target > matrix[row][mid]) left = mid+1; 25 else right = mid-1; 26 } 27 return false; 28 } 29 };