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

Example

For [4, 5, 1, 2, 3] and target=1, return 2.

For [4, 5, 1, 2, 3] and target=0, return -1.

Challenge 

O(logN) time

 

A rotated sorted array has a split point where one side of this point is sorted, the other side is not.

 1 public class Solution {
 2     /** 
 3      *@param A : an integer rotated sorted array
 4      *@param target :  an integer to be searched
 5      *return : an integer
 6      */
 7     public int search(int[] A, int target) {
 8         if(A == null || A.length == 0)
 9         {
10             return -1;
11         }
12         return searchHelper(A, target, 0, A.length - 1);
13     }
14     
15     private int searchHelper(int[] A, int target, int startIdx, int endIdx)
16     {
17         if(startIdx > endIdx)
18         {
19             return -1;
20         }
21         
22         int mid = startIdx + (endIdx - startIdx) / 2;
23         
24         if(A[mid] == target)
25         {
26             return mid;
27         }
28         //right half sorted
29         else if(A[mid] < A[endIdx])
30         {
31             //if target in range of right half
32             if(target > A[mid] && target <= A[endIdx])
33             {
34                 return searchHelper(A, target, mid + 1, endIdx);
35             }
36             //search left half otherwise 
37             else
38             {
39                 return searchHelper(A, target, startIdx, mid - 1);
40             }
41         }
42         //left half sorted 
43         else
44         {
45             //if target in range of left half
46             if(target >= A[startIdx] && target < A[mid])
47             {
48                 return searchHelper(A, target, startIdx, mid - 1);
49             }
50             //search right half otherwise
51             else
52             {
53                 return searchHelper(A, target, mid + 1, endIdx);
54             }
55         }
56     }
57 }

 

 

Related Problems

Search in Rotated Sorted Array II

Search a 2D Matrix

posted @ 2017-11-13 06:23  Review->Improve  阅读(175)  评论(0编辑  收藏  举报