81. Search in Rotated Sorted Array II - jiejackyzhang/leetcode-note GitHub Wiki

Follow up for "33. 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.

引入duplicates后,会对原来的算法造成影响,在判断哪一边是sorted时候。

例如:[1,2,3,1,1,1,1],target=2。

原算法会判断左边是sorted,然后1<2<1不符合,则会判断为2在右边,从而得到错误结果。

因此这里需要将duplicates skip掉。

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