[LeetCode] 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.

geeksforgeeks给出的方法不够elegent。下面的方法非常简便,思路是:通过A[m]和A[l]的比较,确定旋转的幅度。代码如下:

       int search(int A[], int n, int target) {    
            int l = 0, r = n-1;    
            while(l<=r)    
            {    
                 int m = (l+r)/2;    
                 if(A[m] == target) return m;    
                 if(A[m]>= A[l])    
                 {    
                      if(A[l]<=target && target< A[m])    
                           r=m-1;    
                      else    
                           l = m+1;      
                 }    
                 else    
                 {    
                      if(A[m]< target && target<=A[r])    
                           l = m+1;    
                      else    
                           r = m-1;   
                 }    
            }    
            return -1;    
       }

上面的代码只适用于没有重复值的数组。如果数组里有重复值,请看下面的代码:

bool search(int A[], int n, int target){
    int start = 0;  
    int end = n-1;  
    while(start <= end)  
    {  
         int mid = (start+end)/2;  
         if(A[mid] == target) return true;  
         if(A[start] < A[mid])  
         {  
              if(target>=A[start] && target<A[mid])  
                   end = mid-1;  
              else   
                   start = mid+1;  
         }  
         else if(A[start] > A[mid])  
         {  
              if(target>A[mid] && target<=A[end])  
                   start = mid+1;  
              else  
                   end = mid-1;  
         }  
         else //skip duplicate one, A[start] == A[mid]  
              start++;  
    }  
    return false;  
} 



你可能感兴趣的:(LeetCode)