首页 > 代码库 > 33. Search in Rotated Sorted Array

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.

这个题以前是做过的,大概是时间久了,有些荒废,隐约记得是采用二分的思路来解题,看到了博客上有些人的解法思路挺清晰的,借鉴于此

整个思路是采用二分,但是由于有序数组进行了旋转,所以可以使用二分的范围有所变化,可以根据最左值、最右值和中间值的关系,将其划分为三种情况,

如下图所示:

技术分享

在第一种情况下,左值小于中间值,中间值小于右值,整体可以使用二分的策略。

在第二种情况下,左值小于中间值且左值不小于右值,即中间值左侧可以使用二分进行划分。

在第三种情况下,中间值小于右值小于左值和右值(所谓的剩余情况),即中间值的右侧可以使用二分进行划分。

代码如下:

public class Solution {
    public int search(int[] nums, int target) {
 
        if(nums==null||nums.length==0)
            return -1;
        int lo = 0,hi = nums.length-1;
        int mid = (lo+hi)/2;
        while(lo<=hi){
            mid = lo+(hi-lo)/2;
            if(target==nums[mid])
                return mid;
            if(nums[lo]<=nums[hi]){
                if(target>nums[mid])
                    lo = mid+1;
                else
                    hi = mid-1;
            }else if(nums[lo]<=nums[mid]){
                if(nums[lo]<=target&&nums[mid]>target)
                    hi = mid-1;
                else
                    lo = mid+1;
            }else{
                if(nums[mid]<target&&nums[hi]>=target)
                    lo = mid+1;
                else
                    hi = mid-1;
            }
        }
        return -1;
    }
}

更详细的解答可参考链接:http://blog.csdn.net/ljiabin/article/details/40453607

33. Search in Rotated Sorted Array