-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path074_searchMatrix.js
More file actions
51 lines (47 loc) · 962 Bytes
/
Copy path074_searchMatrix.js
File metadata and controls
51 lines (47 loc) · 962 Bytes
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
/**
* https://leetcode.cn/problems/search-a-2d-matrix
* 搜索二维矩阵
*
* 考点:二分查找
*
* j\i 0 1 2 3
* 0 1 3 5 7
* 1 10 11 16 20
* 2 23 30 34 60
*
* 思路:严格递增,可以看成一维数组 O(log(m + n))
*/
var searchMatrix = function(A, target) {
const getVal = (idx) => {
const x = Math.floor(idx / n);
const y = idx % n;
return A[x][y];
}
const m = A.length, n = A[0].length;
let lo = 0, hi = m * n - 1;
while (lo <= hi) {
const mid = lo + ((hi - lo) >> 1);
const val = getVal(mid);
if (val === target) {
return true;
} else if (val > target) {
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return false;
}
// ---- test case ----
console.log(searchMatrix(
[
[ 1, 3, 5, 7],
[10,11,16,20],
[23,30,34,60],
], 3)); // true
console.log(searchMatrix(
[
[ 1, 3, 5, 7],
[10,11,16,20],
[23,30,34,60]
], 13)); // false