-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path74.搜索二维矩阵.ts
50 lines (41 loc) · 905 Bytes
/
74.搜索二维矩阵.ts
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
/*
* @lc app=leetcode.cn id=74 lang=typescript
*
* [74] 搜索二维矩阵
*/
// @lc code=start
function searchMatrix(matrix: number[][], target: number): boolean {
const colIndex = () => {
let rowLow = -1
let rowHigh = matrix.length - 1
while (rowLow < rowHigh) {
const mid = Math.floor((rowLow + 1 + rowHigh) / 2)
if (matrix[mid][0] <= target ) {
rowLow = mid
} else {
rowHigh = mid - 1
}
}
return rowLow
}
let colIdx = colIndex()
if (colIdx < 0) {
return false
}
let col: number[] = matrix[colIdx]
let colLow = 0
let colHigh = col.length - 1
while (colLow <= colHigh) {
let mid = Math.floor((colLow + colHigh) / 2)
if (col[mid] === target) {
return true
}
if (col[mid] > target) {
colHigh = mid - 1
} else {
colLow = mid + 1
}
}
return false
};
// @lc code=end