-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsearch_a2d_matrix2.ts
47 lines (42 loc) · 1.07 KB
/
search_a2d_matrix2.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
// 240. Search a 2D Matrix II
// https://leetcode.com/problems/search-a-2d-matrix-ii/
export default function searchMatrix(
matrix: number[][],
target: number
): boolean {
if (matrix.length === 0) return false;
function traverse({
top,
bottom,
left,
right
}: {
top: number;
bottom: number;
left: number;
right: number;
}): boolean {
if (top >= bottom || left >= right) return false;
const pivotX = Math.trunc((right - left) / 2) + left;
const pivotY = Math.trunc((bottom - top) / 2) + top;
const pivot = matrix[pivotY][pivotX];
if (pivot === target) return true;
if (target < pivot) {
return (
traverse({ top, bottom: pivotY, left, right }) ||
traverse({ top: pivotY, bottom, left, right: pivotX })
);
} else {
return (
traverse({ top, bottom: pivotY + 1, left: pivotX + 1, right }) ||
traverse({ top: pivotY + 1, bottom, left, right })
);
}
}
return traverse({
top: 0,
bottom: matrix.length,
left: 0,
right: matrix[0].length
});
}