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.
Your algorithm’s runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
解题思路
有序数组被分割成两个部分,左边有序和右边有序,且右边比左边小,这样我们可以通过判断目标在哪个部分进行二分查找。注意边界处理,JavaScript代码如下:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
var lv=nums[0],rv=nums[nums.length-1];
var l=0,r=nums.length;
if(target < lv && target > rv) return -1;
else {
if(target >= lv){
while(l < r){
var m = (l+r)/2;
m = Math.floor(m);
if(target == nums[m]) return m;
else if(nums[m]>=lv){
if(target>nums[m]) l=m+1;
else r=m;
}
else if(nums[m]<=rv) r=m;
}
}else if(target <= rv){
while(l < r){
var m = (l+r)/2;
m = Math.floor(m);
if(target == nums[m]) return m;
else if(nums[m]<=rv){
if(target<nums[m]) r=m;
else l=m+1;
}
else if(nums[m]>=lv) l=m+1;
}
}
}
return -1;
};