-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path74. Search a 2D Matrix.js
58 lines (47 loc) · 1.08 KB
/
74. Search a 2D Matrix.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
56
57
58
//74. Search a 2D Matrix
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
function binarySearch(arr, target) {
let left = 0,
right = arr.length - 1,
mid;
while (left <= right) {
mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) return true;
else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
var searchMatrix = function (matrix, target) {
if (matrix.length == 0 || matrix[0].length == 0) return false;
let left = 0,
right = matrix.length - 1,
mid;
while (left < right - 1) {
mid = left + Math.floor((right - left) / 2);
if (matrix[mid][0] === target) {
return true;
} else if (matrix[mid][0] < target) {
left = mid;
} else if (matrix[mid][0] > target) {
right = mid - 1;
}
}
return (
binarySearch(matrix[left], target) || binarySearch(matrix[right], target)
);
};
let matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60],
],
target = 3;
searchMatrix(matrix, target);