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.

Examples:

Given [1, 1, 0, 1, 1, 1] and target = 0, return true.

Given [1, 1, 1, 1, 1, 1] and target = 0, return false.

Notes:

  1. Similar idea with I
  2. Duplicates are allowed, so when A[middle] == A[start] or A[middle] == A[end], we can't cut half, we must move slowly, start++ or end--. Since the duplicates can exist at the beginning or end which includes the target between start and middle or end and middle.
  3. time: O(n), worst case
    public boolean search(int[] A, int target) {
        if (A == null || A.length == 0) {
            return false;
        }

        int start = 0;
        int end = A.length-1;

        while(start+1 < end) {
            int middle = start + (end-start)/2;
            if (A[middle] == target) {
                return true;
            }

            if (A[start] < A[middle]) {
                if (A[start] <= target && target < A[middle]) {
                    end = middle;
                } else {
                    start = middle;
                }
            } else if (A[middle] < A[end]) {
                if (A[middle] < target && target <= A[end]) {
                    start = middle;
                } else {
                    end = middle;   
                }
            } else if (A[start] == A[middle]) {
                start++;
            } else if (A[end] == A[middle]) {
                end--;
            }
        }

        if (A[start] == target || A[end] == target) {
            return true;
        }

        return false;
    }

results matching ""

    No results matching ""