81. Search in Rotated Sorted Array II (JAVA)

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

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
  • Would this affect the run-time complexity? How and why?

 

思路:因为有重复元素,所以不能通过之前的方式判断rotate的地方,需要单独考虑nums[mid] == nums[start]以及nums[mid] == nums[end]的情况,这两种情况分别通过start+1和end-1跳过重复元素。

时间复杂度:在重复元素不多的情况下,并不很影响时间复杂度;担当每次都走的nums[mid] == nums[start]以及nums[mid] == nums[end],那么时间复杂度从O(logn)增至O(n)

class Solution {
    public boolean search(int[] nums, int target) {
        return binarySearch(nums,target,0,nums.length-1);
    }
    
    public boolean binarySearch(int[] nums, int target, int start, int end){
        if(start > end) return false;
        
        int mid = start + ((end-start)>>1);
        if(nums[mid] == target) return true;
        
        if(nums[mid] < nums[start]){ //rotate in the left part
            if(target >= nums[start] || target < nums[mid]) return binarySearch(nums, target, start, mid-1);
            else return binarySearch(nums, target, mid+1, end);
        }
        else if(nums[mid] > nums[end]){ //rotate in the right part
            if(target > nums[mid] || target <= nums[end]) return binarySearch(nums, target, mid+1, end);
            else return binarySearch(nums, target, start, mid-1);
        }
        else if(nums[mid] == nums[start]){
            return binarySearch(nums, target, start+1, end);
        }
        else if(nums[mid] == nums[end]){
            return binarySearch(nums, target, start, end-1);
        }
        else{
            if(target > nums[mid]) return binarySearch(nums, target, mid+1, end);
            else return binarySearch(nums, target, start, mid-1);
        }
    }
}

 

posted on 2019-05-28 11:19  joannae  阅读(116)  评论(0编辑  收藏  举报

导航