您的位置:首页 > 其它

LeetCode 74. Search a 2D Matrix

2016-09-04 15:45 363 查看
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 大。即要找最后一个比target小的数(如果存在的话)。根据二分查找的算法特性,它返回的值应该是跟target 最相邻的数:要么是target 本身,要么是最大的比它小的数,要么是最小的比它大的数。如一列数……3,7,10,20,35…… 要查找11的话,返回的会是10或者20,在第一层查找中返回20是不符合要求的,应该调整一下返回10。

class Solution {
public:
bool searchMatrix(vector<vector<int> >& matrix, int target) {
int low=0,high=matrix.size()-1,mid;
while(low<=high){
mid=(low+high)/2;
if(matrix[mid][0]==target){
return true;
}
else if(matrix[mid][0]<target){
low=mid+1;
}else if(matrix[mid][0]>target){
high=mid-1;
}
}
if(matrix[mid][0]>target){
if(mid>0&&matrix[mid-1][0]<target){
mid-=1;
}
}
vector<int> vec=matrix[mid];
low=0;high=vec.size()-1;
while(low<=high){
mid=(low+high)/2;
if(vec[mid]==target){
return true;
}
else if(vec[mid]<target){
low=mid+1;
}else {
high=mid-1;
}
}
return false;
}
};


优化。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: