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
.
这题很简单
思路:二分法确定target可能在第几行出现。再用二分法在该行确定target可能出现的位置。时间复杂度O(logn+logm)
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m=matrix.size(); int n=matrix[0].size(); int l=0,r=m-1,mid; if(target>matrix[m-1][n-1]||target<matrix[0][0]) return false; while(l<r) { mid=l+(r-l)/2; if(target==matrix[mid][n-1]) return true; else if(target<matrix[mid][n-1]) r=mid; else l=mid+1; } int index=r; l=0; r=n-1; while(l<=r) { mid=l+(r-l)/2; if(target==matrix[index][mid]) return true; else if(target<matrix[index][mid]) r=mid-1; else l=mid+1; } return false; } };