Skip to content

Commit fc8e596

Browse files
committed
[Leet] 34. Find First and Last Position of Element in Sorted Array [medium]
1 parent 1cb546f commit fc8e596

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

허현빈/4주차/260120.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var searchRange = function (nums, target) {
7+
const findBound = (isFirst) => {
8+
let start = 0;
9+
let end = nums.length - 1;
10+
let ans = -1;
11+
12+
while (start <= end) {
13+
let m = Math.floor((start + end) / 2);
14+
if (nums[m] === target) {
15+
ans = m;
16+
if (isFirst) {
17+
end = m - 1;
18+
} else {
19+
start = m + 1;
20+
}
21+
} else if (nums[m] < target) {
22+
start = m + 1;
23+
} else {
24+
end = m - 1;
25+
}
26+
}
27+
return ans;
28+
};
29+
30+
return [findBound(true), findBound(false)];
31+
};

0 commit comments

Comments
 (0)