剑指offer-刷题笔记-中难题JZ4 二维数组中的查找
容易犯错的地方,输入[[]],不能用array.size() == 0判断,可以用temp.size()==0判断,二分查找的判断条件为low<=high,不是low < high
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
for(int i = 0;i < array.size();i++)
{
vector<int> temp = array[i];
if(temp.size() == 0)//判断数组是否为空
{
return false;
}
else if((target <= temp[temp.size() - 1]) && (temp[0] <= target))
{
//二分查找
int low = 0;
int high = temp.size()-1;
int mid = (low + high)/2;
while(low <= high)//注意判断条件
{
if(temp[mid] == target)
{
return true;
}
else if(temp[mid] < target)
{
low = mid + 1;
}else{
high = mid - 1;
}
mid = (low + high)/2;
}
//顺序查找
// for(int j = 0;j < temp.size();j++)
// {
// if(temp[j] == target)
// {
// return true;
// }
// }
}
}
return false;
}
};