From 13c94cfba3f56744e2d49f6cf53f5554a10f4ea8 Mon Sep 17 00:00:00 2001 From: TK Date: Thu, 19 May 2022 21:56:38 -0300 Subject: [PATCH] solve search a 2d matrix --- .../search-a-2d-matrix/search-a-2d-matrix.js | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js diff --git a/coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js b/coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js new file mode 100644 index 00000000..d642fb58 --- /dev/null +++ b/coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js @@ -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; +}