[C++]LeetCode: 44 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》类似,唯一区别就在当A[START] == A[MID]的处理

复杂度: 当有重复数字,最差的情况是O(N)

解析:当A[START] == A[MID]需要全局搜索,逐一移动START. 因为无法判断哪一边是按顺序排列的。

To explain why, consider this sorted array 1111115, which is rotated to 1151111.

Assume left = 0 and mid = 3, and the target we want to search for is 5. Therefore, the condition A[left] == A[mid] holds true, which leaves us with only two possibilities:

  1. All numbers between A[left] and A[right] are all 1's.
  2. Different numbers (including our target) may exist between A[left] and A[right].

As we cannot determine which of the above is true, the best we can do is to move left one step to the right and repeat the process again. Therefore, we are able to construct a worst case input which runs in O(n), for example: the input 11111111...115.

AC Code:

class Solution {
public:
    bool search(int A[], int n, int target) {
        //这次数组中可能有重复数字
        
        int start = 0;
        int end = n - 1;
        
        while(start <= end)
        {
            //防止溢出
            int mid = start + (end - start) / 2;
            if(A[mid] == target) return true;
            if(A[start] < A[mid])
            {
                if(A[start] <= target && target <= A[mid])
                {
                    end = mid - 1;
                }
                else
                {
                    start = mid + 1;
                }
            }
            else if(A[start] > A[mid])
            {
                
                if(A[mid] <= target && target <= A[end])
                {
                    start = mid + 1;
                }
                else
                {
                    end = mid - 1;
                }
            }
            else
                start++;
        }
        
        return false;
        
    }
};


你可能感兴趣的:(LeetCode,array,search,binary)