Skip to content

Commit

Permalink
solve search a 2d matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
imteekay committed May 20, 2022
1 parent c391bf2 commit 13c94cf
Showing 1 changed file with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
function getMiddle(start, end) {
return Math.floor((start + end) / 2);
}

function binarySearch(list, target) {
let start = 0;
let end = list.length - 1;
let middle = getMiddle(start, end);

while (start <= end) {
if (list[middle] === target) {
return true;
} else if (list[middle] > target) {
end = middle - 1;
middle = getMiddle(start, end);
} else {
start = middle + 1;
middle = getMiddle(start, end);
}
}

return false;
}

function searchMatrix(matrix, target) {
let targetRow;

for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) {
let rowFirstNum = matrix[rowIndex][0];
let rowLastNum = matrix[rowIndex][matrix[rowIndex].length - 1];

if (target >= rowFirstNum && target <= rowLastNum) {
targetRow = rowIndex;
}
}

return matrix[targetRow] ? binarySearch(matrix[targetRow], target) : false;
}

0 comments on commit 13c94cf

Please sign in to comment.