题目链接: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.

这道题的要求是在Search in Rotated Sorted Array的基础上允许数组中出现重复元素。

这道题是Search in Rotated Sorted Array的扩展,允许数组中出现重复元素。

思路类似,只不过当A[l] == A[m]的时候,无法判断左侧是否旋转,因此需要遍历l到m之间的元素进行查找,这样,最差的时间复杂度为O(n)。

时间复杂度:O(logn)

空间复杂度:O(1)

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