Find Minimum in Rotated Sorted Array II:带重复的数组中找到升序数列的转折点

来源:互联网 发布:明贤法师 大数据ifeng 编辑:程序博客网 时间:2024/05/29 09:18

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 an array sorted in ascending order 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.


思路:二分查找,只不过因为有重复元素,所以对于这种情况:

[10,1,10,10,10]与[10,10,10,1,10]情况,仅从边界与中值的大小无法判断两种情况的转折点在哪,所以若相等则移动边界。最坏复杂度为O(n)而不是logN。

[10,1,10,10,10]->[1,10,10,10]->二分查找

[10,10,10,1,10]->[10,10,1,10]->[10,1,10]->二分查找

class Solution {    public int findMin(int[] nums) {        if(nums.length==0) return 0;          int start =0;        int end = nums.length-1;        while(start<end){            if(nums[start]<nums[end]){                return nums[start];            }            int mid = (start + end)/2;            if(nums[start]<nums[mid]){                start = mid + 1;            }else if(nums[start]>nums[mid]){                end = mid;            }else{// 如[10,1,10,10,10]与[10,10,10,1,10]情况,仅从边界与中值的大小无法判断两种情况的转折点在哪,所以若相等则移动边界                start++;            }           }        return nums[start];      }}



阅读全文
0 0
原创粉丝点击