-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path74.搜索二维矩阵.js
55 lines (53 loc) · 1.11 KB
/
74.搜索二维矩阵.js
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
/*
* @lc app=leetcode.cn id=74 lang=javascript
*
* [74] 搜索二维矩阵
*/
// @lc code=start
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function (matrix, target) {
if (matrix.length === 0 || matrix[0].length === 0) {
return false
}
let t = 0, b = matrix.length - 1
while (t <= b) {
let m = Math.floor((t + b) / 2)
if (matrix[m][0] < target) {
t = m + 1
} else if (matrix[m][0] > target) {
b = m - 1
} else {
return true
}
}
if (t >= matrix.length) {
t--
} else if (matrix[t][0] > target) {
t--
}
if (t < 0 || t >= matrix.length) {
return false
}
let l = 0, r = matrix[t].length - 1
while (l <= r) {
let m = Math.floor((l + r) / 2)
if (matrix[t][m] < target) {
l = m + 1
} else if (matrix[t][m] > target) {
r = m - 1
} else {
return true
}
}
return false
};
// @lc code=end
console.log(searchMatrix(
[
[1]
], 1
))