-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Create 0034-find-first-and-last-position-of-element-in-sorted-array.js #2620
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
Solved find-first-and-last-position-of-element-in-sorted-array in js.
- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| /** | ||
| * Binary Search | ||
| * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ | ||
| * Time O(log(n)) | Space O(1) | ||
| * @param {number[]} nums | ||
| * @param {number} target | ||
| * @return {number[]} | ||
| */ | ||
| var searchRange = function(nums, target) { | ||
|
|
||
| const result = []; | ||
|
|
||
| result.push(binarySearch(true)); | ||
| result.push(binarySearch(false)); | ||
|
|
||
| function binarySearch(leftBias) { | ||
| let left = 0; | ||
| let right = nums.length - 1; | ||
| let index = -1; | ||
|
|
||
| while(left <= right) { | ||
|
|
||
| const mid = Math.floor((left+right)/2); | ||
|
||
|
|
||
| if(target > nums[mid]) { | ||
| left = mid+1; | ||
| } | ||
| if(target < nums[mid]) { | ||
| right = mid-1; | ||
| } | ||
| // this is the meat of the code | ||
|
||
| if(target === nums[mid]) { | ||
| if(leftBias) { | ||
| index = mid; | ||
| right = mid - 1; | ||
| } else { | ||
| index = mid; | ||
| left = mid + 1; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return index; | ||
| } | ||
|
|
||
| return result; | ||
| }; | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Suggestion: name booleans that prompt a question
isLeftBiasThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just a kind reminder that I updated the code as suggested.