-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsolution.ts
76 lines (62 loc) · 1.44 KB
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* @lc app=leetcode id=34 lang=javascript
*
* [34] Find First and Last Position of Element in Sorted Array
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const searchRange = (nums: number[], target: number): number[] => {
// * ['52 ms', '87.87 %', '35.1 MB', '30 %']
// * pure O(logN)
let left = 0;
let right = nums.length - 1;
// * ---------------- find at least one match
let matchIndex = -1;
while (left <= right) {
const mid = ~~((left + right) / 2);
const midVal = nums[mid];
if (midVal < target) left = mid + 1;
else if (midVal > target) right = mid - 1;
else {
matchIndex = mid;
break;
}
}
// * ---------------- find boundary if it has
const result = [-1, -1];
if (matchIndex !== -1) {
// * ---------------- left boundary
let l = left;
let r = matchIndex;
while (l < r) {
const mid = Math.floor((l + r) / 2);
const midVal = nums[mid];
if (midVal !== target) {
l = mid + 1;
} else {
r = mid;
}
}
result[0] = l;
// * ---------------- right boundary
l = matchIndex;
r = right;
while (l < r) {
const mid = Math.ceil((l + r) / 2);
const midVal = nums[mid];
if (midVal !== target) {
r = mid - 1;
} else {
l = mid;
}
}
result[1] = l;
}
return result;
};
// @lc code=end
export { searchRange };