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.

元素有可能重复,这时候如果A[mid] == A[low]不能确定哪部分是有序的,只能依次查找,退化到O(n)。

class Solution {
public:
    bool search(int A[], int n, int target) {
        int low = 0;
        int up = n - 1;
        int mid;
        while (low <= up) {
            mid = low + (up - low) / 2;
            if (A[mid] == target) {
                return true;
            }
            else if (A[mid] > A[low]) {
                // left part is sorted
                if (A[mid] > target && A[low] <= target) {
                    up = mid - 1;
                }
                else {
                    low = mid + 1;
                }
            }
            else if (A[mid] < A[low]) {
                // right part is sorted
                if (A[mid] < target && A[up] >= target) {
                    low = mid + 1;
                }
                else {
                    up = mid - 1;
                }
            }
            else {
                // don't know which part is sorted
                ++low;
            }
        }
        
        return false;
    }
};

你可能感兴趣的:(LeetCode)