-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsearchForARange.js
67 lines (53 loc) · 1.56 KB
/
searchForARange.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
//这题思路简直不要太简单,可以直接调用函数。
var searchRange = function(nums, target) {
var result = [];
result.push(nums.indexOf(target));
result.push(nums.lastIndexOf(target));
return result;
};
// meothod 2
//自己写一个函数来执行 就好了,前后同时遍历,特别值得一提的是这个方法竟然要比上面那个方法快
var searchRange2 = function(nums, target) {
var result = [];
nums.filter(function(item, index, array){
if(item === target){
result.push(index);
}
});
if(result.length === 0){
result.push(-1, -1);
} else if(result.length === 1){
result[1] = result[0];
} else {
result.splice(1, result.length - 2);
}
return result;
};
// method3
//二分法时间复杂度就是o(lgn),时间上还是比前面两种方法要慢
var searchRange3 = function(nums, target) {
let loPos = -1, hiPos = -1;
searchPos(0, nums.length - 1);
function searchPos(lo, hi) {
if (lo > hi) return;
const mid = parseInt((lo + hi) / 2);
if (nums[mid] === target) {
if (loPos === -1 || loPos > mid) loPos = mid;
if (hiPos === -1 || hiPos < mid) hiPos = mid;
searchPos(lo, mid - 1);
searchPos(mid + 1, hi);
}
if (nums[mid] > target) {
searchPos(lo, mid - 1);
}
if (nums[mid] < target) {
searchPos(mid + 1, hi);
}
}
return [loPos, hiPos];
};