LeetCode: Search a 2D Matrix Solution
Flatten into 1D arrayApproach
Flatten 2D into 1D array and do binary search
Implementation
1const binarySearch = (arr, target) => {2 let n = arr.length3 let [begin, end] = [0, n - 1]4 let res = -156 while (begin <= end) {7 let mid = Math.floor((begin + end) / 2)89 if (arr[mid] > target) {10 end = mid - 111 } else if (arr[mid] < target) {12 begin = mid + 113 } else {14 res = mid15 break16 }17 }1819 return res20}2122var searchMatrix = function (matrix, target) {23 const arr = matrix.flat()2425 return binarySearch(arr, target) === -1 ? false : true26}
References
Similar problems
Search a 2D Matrix II
Comments
Loading comments...
Tags
leetcode
array
matrix
binary search
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Search in Rotated Sorted Array
Time-boxing and other solutions make life easier
Previous Post
LeetCode: Path Sum
Keep subtracting