-
Notifications
You must be signed in to change notification settings - Fork 0
/
240. Search a 2D Matrix II.cpp
71 lines (44 loc) · 1.46 KB
/
240. Search a 2D Matrix II.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty())
return false;
int row = 0;
int col = matrix[0].size()-1;
while(col >=0 && row < matrix.size()) {
if(matrix[row][col] == target)
return true;
else if (matrix[row][col] > target)
col--;
else
row++;
}
return false;
}
};
-------
// Divide & conquer
class Solution {
bool helper(vector<vector<int>>& matrix, int target, int rlow, int rhigh, int clow, int chigh) {
if ((rlow > rhigh) || (clow > chigh))
return false;
int rmid = rlow + (rhigh-rlow)/2;
int cmid = clow + (chigh-clow)/2;
if (matrix[rmid][cmid] == target)
return true;
else if (matrix[rmid][cmid] > target)
return helper(matrix, target, rlow, rhigh, clow, cmid - 1)
|| helper(matrix, target, rlow, rmid-1, cmid, chigh);
else
return helper(matrix, target, rmid+1, rhigh, clow, chigh)
|| helper(matrix, target, rlow, rmid, cmid+1, chigh);
}
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rlow = 0;
int clow = 0;
int chigh = matrix[0].size()-1;
int rhigh = matrix.size()-1;
return helper(matrix, target, rlow, rhigh, clow, chigh);
}
};