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

Search in Rotated Sorted Array

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.

这道题主要思路:先找到pivot,查找pivot过程中前面的已经查找过,只需对后面的进行二分查找即可

 1 public class Solution { 2     public int search(int[] A, int target) { 3         int i = 0; 4         for(; i < A.length; i++){ 5             if(i > 0 && A[i - 1] > A[i])            //找出轴的位置 6                 break; 7             if(A[i] == target) 8                 return i; 9         }10         if(i == A.length)                            //没有找到11             return -1;12         //从轴的位置到最后开始二分查找从i的位置开始到length - 113         int low = i;14         int high = A.length - 1;15         int middle;16         while(low <= high){17             middle = (low + high) / 2;18             if(A[middle] == target)19                 return middle;20             else if(A[middle] > target){        //前半段找21                 high = middle - 1;22             }else{                                //后半段找23                 low = middle + 1;24             }25         }26         27         return  -1;28     }29 }

 

Search in Rotated Sorted Array