-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsearch-for-a-range.js
46 lines (45 loc) · 1.09 KB
/
search-for-a-range.js
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
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
const length = nums.length;
if (length < 1) {
return [-1, -1];
}
if (length < 2) {
if (nums[0] === target) {
return[0, 0];
}
return [-1, -1];
}
if (target < nums[0] || target > nums[length - 1]) {
return [-1, -1];
}
var start = 0;
var end = length - 1;
while (start <= end) {
var middle = Math.ceil((start + end) / 2);
if (target < nums[middle]) {
end = middle - 1;
} else if (target > nums[middle]) {
start = middle + 1;
} else {
return getIndex(nums, target, middle);
}
}
return [-1, -1];
};
var getIndex = function(nums, target, middle) {
var length = nums.length;
var start = middle;
var end = middle
while (start >= 1 && nums[start - 1] === nums[middle]) {
start --;
}
while (end <= length - 2 && nums[end + 1] === nums[middle]) {
end ++;
}
return [start, end];
};