LeetCode: Search a 2D Matrix Solution

Flatten into 1D array

Approach

Flatten 2D into 1D array and do binary search

Implementation

1const binarySearch = (arr, target) => {
2 let n = arr.length
3 let [begin, end] = [0, n - 1]
4 let res = -1
5
6 while (begin <= end) {
7 let mid = Math.floor((begin + end) / 2)
8
9 if (arr[mid] > target) {
10 end = mid - 1
11 } else if (arr[mid] < target) {
12 begin = mid + 1
13 } else {
14 res = mid
15 break
16 }
17 }
18
19 return res
20}
21
22var searchMatrix = function (matrix, target) {
23 const arr = matrix.flat()
24
25 return binarySearch(arr, target) === -1 ? false : true
26}

References

Original problem

Similar problems

Search a 2D Matrix II

Comments

Loading comments...

Tags

leetcode

array

matrix

binary search

Next Post

LeetCode: Search in Rotated Sorted Array

Time-boxing and other solutions make life easier

Previous Post

LeetCode: Path Sum

Keep subtracting

HoningJS

Search Posts