forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#2620 from aadil42/patch-63
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
javascript/0034-find-first-and-last-position-of-element-in-sorted-array.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, nums, target)); | ||
result.push(binarySearch(false, nums, target)); | ||
|
||
return result; | ||
}; | ||
|
||
var binarySearch = (isLeftBias, nums, target) => { | ||
let left = 0; | ||
let right = nums.length - 1; | ||
let index = -1; | ||
|
||
while(left <= right) { | ||
|
||
const mid = (left + right) >> 1; | ||
|
||
if(target > nums[mid]) { | ||
left = mid+1; | ||
} | ||
if(target < nums[mid]) { | ||
right = mid-1; | ||
} | ||
|
||
const isTarget = target === nums[mid]; | ||
if(isTarget) { | ||
if(isLeftBias) { | ||
index = mid; | ||
right = mid - 1; | ||
} else { | ||
index = mid; | ||
left = mid + 1; | ||
} | ||
} | ||
} | ||
return index; | ||
} |