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.

Example:

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

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

Solution:

Similar to Find Minimum in Rotated Sorted Array II. If we found duplicate, we need to move start or end. In ideal case, we should set start = mid or end = mid. However, since the array is rotated, the duplicate numbers could be appeared in both side of the array, for exemple: [4,4,5,6,7,0,1,2,4,4]. Therefore, we can only move start or end by one step at a time. For instance: if nums[mid] == nums[start], start++. If nums[mid] == nums[end], end--.

Code:

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

results matching ""

    No results matching ""