代码
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int m = array.size();
int n = array[0].size();
if (m==0) return false;
if (n==0) return false;
int r=0,c=n-1;
while (r<m && c>=0){
if (array[r][c]==target) return true;
else if (array[r][c]<target) ++r;
else --c;
}
return false;
}
};
思路
使用二分查找,将初始元素定位在右上角。
- 等于target就return。
- 如果小于target,就将行数增加。
- 如果大于target,就将列数减小。