LeetCode: Find First And Last Position Of Element In Sorted Array Solution
1/**2 * @param {number[]} nums3 * @param {number} target4 * @return {number[]}5 */6var searchRange = function (nums, target) {7 const binarySearchLeft = (nums, target) => {8 let [left, right, index] = [0, nums.length - 1, -1]9 while (left <= right) {10 const mid = Math.floor((left + right) / 2)11 if (nums[mid] >= target) {12 right = mid - 113 } else {14 left = mid + 115 }16 if (nums[mid] === target) {17 index = mid18 }19 }2021 return index22 }23 const binarySearchRight = (nums, target) => {24 let [left, right, index] = [0, nums.length - 1, -1]25 while (left <= right) {26 const mid = Math.floor((left + right) / 2)27 if (nums[mid] <= target) {28 left = mid + 129 } else {30 right = mid - 131 }32 if (nums[mid] === target) {33 index = mid34 }35 }3637 return index38 }3940 return [binarySearchLeft(nums, target), binarySearchRight(nums, target)]41}4243var searchRange = function (nums, target) {44 return [nums.indexOf(target), nums.lastIndexOf(target)]45}
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.
Next Post
LeetCode: Powerful Integers
May 1, 2021
Previous Post
LeetCode: Unique Paths II
Apr 28, 2021