154. Find Minimum in Rotated Sorted Array II

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.

153的扩展。二分查找,如果mid小于最右侧,证明右边是sort好的,则最小值必定在左边。

如果mid大于最右侧,则证明左侧最小值被rotate到了右侧,则最小值必定在右侧。

如果中间值等于右侧值,则无法判断哪边是sort好的,比如1,2,3,3,3,3,也可以是3,3,3,3,1,2,3。因此需要一个个的收缩,最坏情况下时间复杂度为O(n).

public class Solution {
  public int findMin(int[] num) {
    int min = num[0];
    int left = 0;
    int right = num.length - 1;
    while (left <= right) {
      int mid = left + (right - left) / 2;
      if (num[mid] < num[right]) {
        right = mid - 1;
      } else if (num[mid] > num[right]) {
        left = mid + 1;
      } else {
        right --;
      }
      min = Math.min(min, num[mid]);
    }
    return min;

  }
}

posted on 2015-04-15 02:01  shini  阅读(95)  评论(0编辑  收藏  举报

导航