Search in Rotated Sorted Array II [LeetCode]

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

Summary: Almost the same to Search in Rotated Sorted Array without duplicates, but careful about the corner case like [1311], we should search both left half and right half. So, in this case, the run-time complexity will between O(logN) to O(N).

 1 class Solution {
 2 public:
 3     bool search(int A[], int n, int target) {
 4         if(n == 0)
 5             return false;
 6         if(n == 1) {
 7             if(A[0] == target )
 8                 return true;
 9             else 
10                 return false;
11         }
12         
13         int median = n/2;
14         if(A[median] == target)
15             return true;
16         if(A[0] == target)
17             return true;
18             
19         if(A[0] < A[median] && target > A[0] && target < A[median] || 
20             (A[0] > A[median] && (target > A[0] || target < A[median]))){
21               return search(A + 1, median - 0, target);  
22             }else if(A[0] == A[median]){
23                 bool ret1 = search(A + 1, median - 0, target);      
24                 bool ret2 = false;
25                 if(n - median - 1 <= 0)
26                     ret2 = false;
27                 
28                 ret2 = search(A + median + 1, n - median -1, target);
29                 return ret1 || ret2;
30             }else{
31                 if(n - median - 1 <= 0)
32                     return false;
33                 
34                 return search(A + median + 1, n - median -1, target);
35             }
36     }
37 };

 

posted @ 2013-11-05 13:02  假日笛声  阅读(552)  评论(0编辑  收藏  举报