Skip to content

Commit 7204e6c

Browse files
committed
add 34 ts solution
1 parent e37d19a commit 7204e6c

File tree

1 file changed

+33
-0
lines changed
  • Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function searchRange(nums: number[], target: number): number[] {
2+
3+
const max = binarySearch(nums, target, true);
4+
5+
if (max !== undefined) {
6+
const min = binarySearch(nums, target, false);
7+
return [min!, max];
8+
}
9+
return [-1, -1];
10+
11+
function binarySearch(nums: number[], target: number, flag: boolean): number | undefined {
12+
let position: number | undefined;
13+
let left = 0;
14+
let right = nums.length - 1;
15+
while (left <= right) {
16+
let mid = Math.floor((left + right) / 2);
17+
if (nums[mid] > target) {
18+
right = mid - 1;
19+
} else if (nums[mid] < target) {
20+
left = mid + 1;
21+
} else {
22+
position = mid;
23+
if (flag) {
24+
left = left + 1;
25+
} else {
26+
right = right - 1;
27+
}
28+
}
29+
}
30+
return position;
31+
}
32+
33+
};

0 commit comments

Comments
 (0)