LeetCode: Search A 2d Matrix II Solution
1function binarySearch(A, k) {2 const N = A.length3 let begin = 04 let end = N - 15 while (begin <= end) {6 let mid = Math.floor((begin + end) / 2)7 if (A[mid] === k) {8 return true9 } else if (A[mid] > k) {10 end = mid - 111 } else if (A[mid] < k) {12 begin = mid + 113 }14 }15 return false16}1718/**19 * @param {number[][]} matrix20 * @param {number} target21 * @return {boolean}22 */23// O(m * logn)24var searchMatrix = function (matrix, target) {25 let m = matrix.length26 let n = matrix[0].length27 let res = false2829 for (let i = 0; i < m; i++) {30 const arr = matrix[i]31 if (binarySearch(arr, target)) {32 res = true33 }34 }3536 return res37}3839// O(m + n)40var searchMatrix = function (matrix, target) {41 let m = matrix.length42 let n = matrix[0].length43 let i = 044 let j = n - 14546 while (j >= 0 && i < m) {47 if (matrix[i][j] === target) {48 return true49 } else if (matrix[i][j] < target) {50 // can't be at the current col so:51 i++52 } else if (matrix[i][j] > target) {53 // can't be at the current row so:54 j--55 }56 }5758 return false59}
Comments
Loading comments...
Tags
leetcode
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.