154. Find Minimum in Rotated Sorted Array II

来源:互联网 发布:电脑上解压缩软件 编辑:程序博客网 时间:2024/06/06 21:15

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

The array may contain duplicates.

Solution 1 Binary Search

public int findMin(int[] nums) {int start = 0, end = nums.length - 1;while (start < end) {int mid = (start + end) / 2;if (nums[mid] < nums[end]) {// cannot be <=end = mid;} else if (nums[mid] > nums[end]) {start = mid + 1;} else {end--; // nums[mid]=nums[end] no idea, but we can eliminate// nums[end];}}return nums[start];// this is start}

Solution 2 Recursion

public int findMin2(int[] nums) {        return search(nums, 0, nums.length - 1);    }    public int search(int[]nums, int start, int end){        if (start == end) {return nums[start];}        int mid = (start + end) / 2;        if(nums[mid] < nums[end]){            return search(nums, start, mid);        }else if(nums[mid] > nums[end]){            return search(nums, mid + 1, end);        }else{            return search(nums, start, end - 1);        }    }



0 0
原创粉丝点击