LeetCode: Binary Search Solution
Classic problemApproach
Given that the array is sorted ascending
Compare the middle element with
target
- if greater than, continue searching on the left
- if smaller than, continue searching on the right
- else we are done
Implementation
1var search = function (nums, target) {2 const n = nums.length3 let lo = 04 let hi = n - 15 let res = -167 while (lo <= hi) {8 let mid = Math.floor((lo + hi) / 2)9 if (nums[mid] > target) {10 hi = mid - 111 } else if (nums[mid] < target) {12 lo = mid + 113 } else {14 res = mid15 break16 }17 }1819 return res20}
References
Comments
Loading comments...
Tags
leetcode
array
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.