-
-
Notifications
You must be signed in to change notification settings - Fork 81
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |