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.

 

public class Solution {
    public boolean search(int[] nums, int target) {
        int start = 0;
        int end = nums.length-1;
        return search(nums, target, start, end);
    }

	private boolean search(int[] nums, int target, int start, int end) {
		if (start>end) {
			return false;
		}
		int mid = (start+end)/2;
		if (target == nums[mid]) {
			return true;
		}
		if (nums[mid] == nums[end]) {
		    return search(nums, target, start, mid-1) || search(nums, target, mid+1, end);
		} else if (nums[mid] > nums[end]) {
			if (target<nums[mid] && target>=nums[start]) {
				return search(nums, target, start, mid-1);
			} else {
				return search(nums, target, mid+1, end);
			}
		} else {
			if (target>nums[mid] && target<=nums[end]) {
				return search(nums, target, mid+1, end);
			} else {
				return search(nums, target, start, mid-1);
			}
		}
	}
}

 

你可能感兴趣的:(search)