Search in Rotated Sorted Array [LeetCode]

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.

Summary: Binary search can apply to a rotated sorted array, just by analysis of its property.

 1 class Solution {

 2 public:

 3     int search(int A[], int n, int target) {

 4         if(n == 0)

 5             return -1;

 6         if(n == 1) {

 7             if(A[0] == target)

 8                 return 0;

 9             else

10                 return -1;

11         }

12         

13         int median = n / 2;

14         if(A[median] == target)

15             return median;

16             

17         if(A[0] < A[median] && target >= A[0] && target < A[median] ||

18             (A[0] > A[median] && (target >= A[0] || target < A[median]))){

19             return search(A, median, target);

20         }else{

21             if(median + 1 >= n)

22                 return -1;

23             else{

24                 int ret =  search(A + median + 1, n - median -1, target);

25                 if(ret == -1)

26                     return -1;

27                 else 

28                     return median + 1 + ret;

29             }

30         }

31     }

32 };

 

你可能感兴趣的:(LeetCode)