-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchInRotatedArray.js
60 lines (49 loc) · 1.27 KB
/
SearchInRotatedArray.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
function SearchInRotatedArray(nums, target) {
//Use binary search
let left = 0; //first element
let right = nums.length - 1; //last element
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const value = nums[mid];
if (value ===target) {
return mid;
}
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target <= nums[mid]) {
right = mid - 1;
} else {
// target is in the right
left = mid + 1;
}
//if right is sorted
} else {
if (target >= nums[mid] && target <= nums[right]) {
// target is in the right
left = mid + 1;
} else {
// target is in the left
right = mid - 1;
}
}
}
return -1
}
console.log(SearchInRotatedArray([4,5,6,7,0,1,2],0))
var search = function(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const value = nums[mid];
if (value === target) {
return mid;
}
if ((nums[left] <= value && target >= nums[left] && target <= value) ||
(nums[left] > value && (target >= nums[left] || target <= value))) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
};