Leetcode-Search in Rotated Sorted Array

LiBlog發表於2014-11-21

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.

Analysis:

Suppose we have three pointers:start, mid and end. There are three case for the array between start and end:

1. A[mid] < A[start]: Rotated, the maximum value is on the left of mid. If target < A[mid], then we search the left part; if target > A[mid], we then have two situations: (a) target <= A[end], we search the right part; (b) target > A[end], search the left part.

2. A[mid] > A[end]: Rotated, the maximum value is on the right of mid. target > A[mid]: search the left part; target < A[mid] && < A[start]: search the right part; target < A[mid] && >= A[start]: search the left part.

3. Otherwise: Not rotated. Just perform normal binary search.

Solution:

 1 public class Solution {
 2     public int search(int[] A, int target) {
 3         if (A.length==0) return -1;
 4 
 5         int start = 0, end = A.length-1;
 6         int mid = -1;
 7 
 8         while (start<=end){
 9             mid = (start+end)/2;
10             if (A[mid]==target) return mid;
11 
12             if (A[mid]<A[start]){
13                 if (target<A[mid])
14                     end = mid-1;
15                 else if (target<=A[end])
16                     start = mid+1;
17                 else end = mid-1;
18                 continue;
19             }
20 
21             if (A[mid]>A[end]){
22                 if (target>A[mid]) start = mid+1;
23                 else if (target>=A[start]) end = mid-1;
24                 else start = mid+1;
25                 continue;
26             }
27 
28             if (target<A[mid]) end = mid-1;
29             else start = mid+1;
30         }
31 
32         return -1;
33     }
34 }

 

相關文章