-
Notifications
You must be signed in to change notification settings - Fork 4
/
search-in-rotated-sorted-array.js
67 lines (61 loc) · 1.44 KB
/
search-in-rotated-sorted-array.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
var DEBUG = process.env.DEBUG;
function nfind(nums, st, ed, target) {
if (ed - st <= 2) {
for (var i = st; i < ed; i++)
if (nums[i] === target) return i;
return -1;
}
// at least 3 nums
var mid = (st + ed) >> 1;
if (nums[mid] === target) return mid;
if (nums[mid] < target) {
return nfind(nums, mid+1, ed, target);
} else {
return nfind(nums, st, mid, target);
}
}
function find(nums, st, ed, target) {
if (ed - st <= 2) {
for (var i = st; i < ed; i++)
if (nums[i] === target) return i;
return -1;
}
// at least 3 nums
var mid = (st + ed) >> 1;
if (nums[mid] === target) return mid;
if (nums[mid] > nums[st]) {
if (target >= nums[st] && target < nums[mid]) {
return nfind(nums, st, mid, target);
} else {
return find(nums, mid, ed, target);
}
} else {
if (target > nums[mid] && target < nums[st]) {
return nfind(nums, mid, ed, target);
} else {
return find(nums, st, mid+1, target);
}
}
}
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
return find(nums, 0, nums.length, target);
};
function test(f) {
for (var i = 0; i <= 7; i++)
console.log(f([4, 5, 6, 7, 0, 1, 2], i));
[
[[4,5,6,7,0,1,2], -2],
[[2, 1], -2],
[[2, 1], 1],
[[2, 1], 0],
[[], 0],
].forEach(function (input) {
console.log(f.apply(undefined, input));
});
}
if (DEBUG) test(search);