Skip to content

Commit 0d6f0ea

Browse files
authored
Merge pull request #2620 from aadil42/patch-63
2 parents 285999d + fe9c706 commit 0d6f0ea

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Binary Search
3+
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
4+
* Time O(log(n)) | Space O(1)
5+
* @param {number[]} nums
6+
* @param {number} target
7+
* @return {number[]}
8+
*/
9+
var searchRange = function(nums, target) {
10+
11+
const result = [];
12+
13+
result.push(binarySearch(true, nums, target));
14+
result.push(binarySearch(false, nums, target));
15+
16+
return result;
17+
};
18+
19+
var binarySearch = (isLeftBias, nums, target) => {
20+
let left = 0;
21+
let right = nums.length - 1;
22+
let index = -1;
23+
24+
while(left <= right) {
25+
26+
const mid = (left + right) >> 1;
27+
28+
if(target > nums[mid]) {
29+
left = mid+1;
30+
}
31+
if(target < nums[mid]) {
32+
right = mid-1;
33+
}
34+
35+
const isTarget = target === nums[mid];
36+
if(isTarget) {
37+
if(isLeftBias) {
38+
index = mid;
39+
right = mid - 1;
40+
} else {
41+
index = mid;
42+
left = mid + 1;
43+
}
44+
}
45+
}
46+
return index;
47+
}

0 commit comments

Comments
 (0)