Tuesday, June 17, 2014

Search in rotated sorted array -- Leetcode

Question:
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.
Answer:
  1. public int search(int[] A, int target) {  
  2.     if(A==null || A.length==0)  
  3.         return -1;  
  4.     int l = 0;  
  5.     int r = A.length-1;  
  6.     while(l<=r)  
  7.     {  
  8.         int m = (l+r)/2;  
  9.         if(target == A[m])  
  10.             return m;  
  11.         if(A[m]<A[r])  
  12.         {  
  13.             if(target>A[m] && target<=A[r])  
  14.                 l = m+1;  
  15.             else  
  16.                 r = m-1;  
  17.         }  
  18.         else  
  19.         {  
  20.             if(target>=A[l] && target<A[m])  
  21.                 r = m-1;  
  22.             else  
  23.                 l = m+1;                      
  24.         }  
  25.     }  
  26.     return -1;  
  27. }  

No comments:

Post a Comment