forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-a-2d-matrix.cpp
117 lines (98 loc) · 2.99 KB
/
search-a-2d-matrix.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Time: O(logm + logn)
// Space: O(1)
class Solution {
public:
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
if (matrix.empty()) {
return false;
}
// Treat matrix as 1D array.
const int m = matrix.size();
const int n = matrix[0].size();
int left = 0;
int right = m * n - 1;
// Find min of left s.t. matrix[left / n][left % n] >= target
while (left <= right) {
int mid = left + (right - left) / 2;
if (matrix[mid / n][mid % n] >= target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// Check if matrix[left / n][left % n] equals to target.
if (left != m * n && matrix[left / n][left % n] == target) {
return true;
}
return false;
}
};
class Solution2 {
public:
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
if (matrix.empty()) {
return false;
}
// Treat matrix as 1D array.
const int m = matrix.size();
const int n = matrix[0].size();
int left = 0;
int right = m * n;
// Find min of left s.t. matrix[left / n][left % n] >= target
while (left < right) {
int mid = left + (right - left) / 2;
if (matrix[mid / n][mid % n] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
// Check if matrix[left / n][left % n] equals to target.
if (left != m * n && matrix[left / n][left % n] == target) {
return true;
}
return false;
}
};
class Solution3 {
public:
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
if (matrix.empty()) {
return false;
}
// Treat matrix as 1D array.
const int m = matrix.size();
const int n = matrix[0].size();
int left = -1;
int right = m * n;
// Find min of right s.t. matrix[right / n][right % n] >= target
while (right - left > 1) {
int mid = left + (right - left) / 2;
if (matrix[mid / n][mid % n] >= target) {
right = mid;
} else {
left = mid;
}
}
// Check if matrix[right / n][right % n] equals to target.
if (right != m * n && matrix[right / n][right % n] == target) {
return true;
}
return false;
}
};