33. Search in Rotated Sorted Array
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.
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number} 5 */ 6 var search = function(A, target) { 7 //有序数组查找固定值,第一反应就是二分。 8 var lo = 0; 9 var hi = A.length - 1;10 11 while (lo < hi) {12 var mid = Math.floor((lo + hi) / 2);13 if (A[mid] == target) return mid;14 15 if (A[lo] <= A[mid]) {16 if (target >= A[lo] && target < A[mid]) {17 hi = mid - 1;18 } else {19 lo = mid + 1;20 }21 } else {22 if (target > A[mid] && target <= A[hi]) {23 lo = mid + 1;24 } else {25 hi = mid - 1;26 }27 }28 }29 return A[lo] == target ? lo : -1;30 };