题目:Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
每一行递增;每一行第一个数字比前一行最后一个数字大。
[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]Given target =
3
,
return true
.思路:二分法
解题过程中注意一点,求的mid值之后,如何定位到具体的每一行与每一列,一开始,我用mid/m 和 mid%n ,后来发现不对,应该是 mid/n,mid/m 求解的是对应的哪一列
代码:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty()||matrix[0].empty()){ return false; } int m=matrix.size(),n=matrix[0].size(); int start=0,end=m*n-1; //真正开始判断 while (start<=end){ int mid = (start+end)/2; int i=mid/n,j=mid%n; if (matrix[i][j]==target){ return true; } if (matrix[i][j]<target){ start=mid+1; } else{ end=mid-1; } } return false; } };