81.Search in Rotated Sorted Array II

Follow upfor "Search in Rotated Sorted Array":
What ifduplicatesare allowed?

Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

Analysis

Same idea as 33 (with no duplicates); The only change is when left == mid or right == mid, we do not know which part is sorted, so we just either increase left index by 1 or decrease right index by one.

Worst case could be O(n), for cases like [3, 3, 3, 3, 3, 3, 3, 1, 3];

Solution

public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return true;
            }
            else if (nums[mid] == nums[left]) {
                left++;
            } else if (nums[mid] > nums[left]) {
                if (nums[mid] >= target && target >= nums[left]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                if (nums[mid] <= target && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return false;
    }

results matching ""

    No results matching ""