-
Notifications
You must be signed in to change notification settings - Fork 1
/
search-a-2d-matrix-ii.js
30 lines (28 loc) · 1.22 KB
/
search-a-2d-matrix-ii.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
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
const rowLength = matrix.length;
const columnLength = matrix[0].length;
const recSearchMatrix = (rowStart, rowEnd, columnStart, columnEnd) => {
if (rowStart >= rowEnd || columnStart >= columnEnd) {
return false;
}
let rowPivot = rowStart;
const columnPivot = Math.floor((columnStart + columnEnd) / 2);
while (rowPivot < rowEnd) {
if (matrix[rowPivot][columnPivot] === target) {
return true;
} else if (matrix[rowPivot][columnPivot] > target) {
return recSearchMatrix(rowStart, rowEnd, columnStart, columnPivot);
} else if (rowPivot + 1 < rowEnd && matrix[rowPivot][columnPivot] < target && matrix[rowPivot + 1][columnPivot] > target) {
return recSearchMatrix(rowStart, rowPivot + 1, columnPivot + 1, columnEnd) || recSearchMatrix(rowPivot, rowEnd, columnStart, columnPivot);
}
rowPivot++;
}
return recSearchMatrix(rowStart, rowEnd, columnPivot + 1, columnEnd);
}
return recSearchMatrix(0, rowLength, 0, columnLength);
};