Leetcode Search in Rotated Sorted Array

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/search-in-rotated-sorted-array/
题目:

Suppose a sorted array 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、二分查找 根据左右跟中间比较的结果 对有序的部分采用二分查找。

算法

public int search(int[] nums, int target) {  
    int left = 0,right = nums.length-1,mid = 0;  
    while(left<=right){  
        mid = left+(right-left)/2;  
        if(nums[mid]==target){  
            return mid;  
        }  
        if(nums[left]<nums[mid]){ //则left到mid有序  
            if(nums[left]==target){  
                return left;  
            }  
            if(nums[left]<=target&&target<nums[mid]){ //若target在left到mid之间  
                right = mid;  
            }else{  
                left = mid + 1;  
            }  
        }else{//则mid到right之间有序  
            if(target==nums[right]){  
                return right;  
            }  
            if(nums[mid]<target&&target<=nums[right]){ //若target在mid到right之间  
                left = mid + 1;  
            }else{  
                right = mid-1;  
            }  
        }  
    }  
    return -1;  
}  


以上是关于Leetcode Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode048. Rotate Image

LeetCode矩阵旋转Rotate Image

Leetcode Search in Rotated Sorted Array

19.2.7 [LeetCode 48] Rotate Image

[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array

[LeetCode&Python] Problem 700. Search in a Binary Search Tree