28.earch in Rotated Sorted Array(排序旋转数组中查找)

Level:

  Medium

题目描述:

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

思路分析:

  有序旋转数组,设置两个指针,left和right,分别指向数组的左端和右端,求数组的mid,如果mid的值大于left的值,那么旋转点在mid后面,如果小于left,则证明旋转点在mid前面。

  如果旋点在mid的后面,并且target的值大于left处的值,小于mid处的值,那么接下来就可以在left到mid之间进行二分查找target,否则对mid+1到right这部分数组进行递归操作。

  如果旋点在mid的前面,并且target的值大于mid处的值,小于right处的值,那么接下来就可以在mid到right之间进行二分查找target,否则对left到mid-1这部分数组进行递归操作。

代码:

public class Solution{
    public int search(int []nums,int target){
        if(nums==null||nums.length==0)
            return -1;
        int res=find(nums,0,nums.length-1,target);
        return res;
    }
    public int find(int []nums,int left,int right,int target){
        if(nums[left]==target)
            return left;
        if(nums[right]==target)
            return right;
        int mid=(left+right)/2;
        if(nums[mid]==target)
            return mid;
        if(left>right)
            return -1;
        if(nums[mid]>nums[left]){ //证明旋转点在mid后面
            if(target>nums[left]&&target<nums[mid]){
                return binarySearch(nums,left,mid-1,target);
            }else{
                return find(nums,mid+1,right,target);
            }
            
        }
        if(nums[mid]<nums[left]){ //证明旋转点在mid的前面
            if(target>nums[mid]&&target<nums[right]){
                return binarySearch(nums,mid+1,right,target);
            }else{
                return find(nums,left,mid-1,target);
            }
        }
        return -1;
    }
    public int binarySearch(int []nums,int left,int right,int target){
        if(left<=right){
            int mid=(left+right)/2;
            if(nums[mid]==target)
                return mid;
            if(target>nums[mid]){
                return binarySearch(nums,mid+1,right,target);
            }
            if(target<nums[mid]){
                return binarySearch(nums,left,mid-1,target);
            }
        }
        return -1;
    }
}
上一篇:LeetCode算法题-Rotated Digits(Java实现)


下一篇:LeetCode-153 Find Minimum in Rotated Sorted Array