[LeetCode] Search in Rotated Sorted Array II

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.

 1 class Solution {
 2 public:
 3     int findPos(int a[], int left, int right)
 4     {
 5         if (left > right)
 6             return -1;
 7             
 8         int mid = left + (right - left) / 2;
 9         
10         if (a[left] < a[mid])
11         {
12             int pos = findPos(a, mid + 1, right);
13             if (pos == -1)
14                 return left;
15             else
16                 return a[pos] <= a[left] ? pos : left;
17         }
18         else if (a[left] > a[mid])
19         {
20             int pos = findPos(a, left, mid - 1);
21             if (pos == -1)
22                 return mid;
23             else
24                 return a[pos] < a[mid] ? pos : mid;
25         }
26         else
27         {
28             int pos1 = findPos(a, left, mid - 1);
29             int pos2 = findPos(a, mid + 1, right);
30             if (pos1 == -1 && pos2 == -1)
31                 return mid;
32             else if (pos1 == -1)
33                 return a[mid] < a[pos2] ? mid : pos2;
34             else if (pos2 == -1)
35                 return a[mid] <= a[pos1] ? mid : pos1;
36             else
37             {
38                 if (a[pos1] < a[pos2])
39                     return a[mid] <= a[pos1] ? mid : pos1;
40                 else
41                     return a[mid] < a[pos2] ? mid : pos2;
42             }
43         }
44     }
45     
46     bool bsearch(int a[], int left, int right, int key)
47     {
48         if (left > right)
49             return false;
50             
51         int mid = left + (right - left) / 2;
52         
53         if (a[mid] == key)
54             return true;
55         else if (a[mid] < key)
56             return bsearch(a, mid + 1, right, key);
57         else
58             return bsearch(a, left, mid - 1, key);            
59     }
60     
61     bool search(int A[], int n, int target) {
62         // Start typing your C/C++ solution below
63         // DO NOT write int main() function
64         int pos = findPos(A, 0, n - 1);
65         return bsearch(A, 0, pos - 1, target) || bsearch(A, pos, n - 1, target);
66     }
67 };
posted @ 2012-11-25 14:40  chkkch  阅读(775)  评论(0编辑  收藏  举报