-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
74 lines (64 loc) · 1.95 KB
/
res.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
68
69
70
71
72
73
74
/**
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
*
* You are given a target value to search. If found in the array return its index, otherwise return -1.
*
* You may assume no duplicate exists in the array.
*
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-02-26 23:34:54
* @version $Id$
*
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
let search = function(nums, target) {
let count = 0,
curIndex = 0,
preIndex = 0,
larger = true,
numslen = nums.length;
if (numslen === 0) {
return -1;
}
if (nums[0] < target) {
larger = false;
}
// 需要考虑两点: 到了原始排序数组边缘跳转, 或者 target 不存在对比出现大小反转的情况
while (count < numslen) {
// Found the target
if (nums[curIndex] === target) {
return curIndex;
} else if (nums[curIndex] > target) {
if (!larger || nums[curIndex] > nums[preIndex]) {
return -1;
}
preIndex = curIndex;
curIndex = (curIndex-1+numslen)%numslen;
} else {
if (larger || nums[curIndex] < nums[preIndex]) {
return -1;
}
preIndex = curIndex;
curIndex = (curIndex+1)%numslen;
}
count += 1;
}
return -1;
};
const search_2 = (nums, target) => {
let lo = 0, hi = nums.length - 1;
while (lo < hi) {
let mid = (lo + hi) >> 1;
if (nums[0] <= nums[mid] && (target > nums[mid] || target < nums[0])) {
lo = mid + 1;
} else if (target < nums[0] && target > nums[mid]) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo == hi && nums[lo] == target ? lo : -1;
}