`
hcx2013
  • 浏览: 88948 次
社区版块
存档分类
最新评论

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);
			}
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics