-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path剑指offer 1 二维数组中的查找
41 lines (39 loc) · 1.28 KB
/
剑指offer 1 二维数组中的查找
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
// O(n+m)
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int rows = array.size(), cols = array[0].size();
int row=rows-1,col=0;
while(row>=0 && col<cols){
if(array[row][col]==target) return true;
else if(array[row][col]>target) row--;
else col++;
}
return false;
}
};
// O(nlogm)
// O(n+m)
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if(array.size()==0) return false;
int nrows = array.size(), ncols= array[0].size();
for(int i=0;i<nrows;i++){
int low=0;
int high=ncols-1;
while(low<=high){
int mid=(low+high)/2;
if(target>array[i][mid])
low=mid+1;
else if(target<array[i][mid])
high=mid-1;
else
return true;
}
}
return false;
}
};