码迷,mamicode.com
首页 > 其他好文 > 详细

154. Find Minimum in Rotated Sorted Array II

时间:2019-09-13 10:39:49      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:complex   ble   --   ica   duplicate   problem   order   known   input   

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.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

  • This is a follow up problem to Find Minimum in Rotated Sorted Array.
  • Would allow duplicates affect the run-time complexity? How and why?
    class Solution {
        public int findMin(int[] nums) {
            int left = 0;
            int right = nums.length - 1;
            while (left < right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] < nums[right]) {
                    right = mid;
                } else if (nums[mid] > nums[right]) {
                    left = mid + 1;
                } else {
                    --right;
                }
            }
            return nums[left];
        }
    }

    和search一样,如果有重复元素,right=mid,就right--减少数组元素。

154. Find Minimum in Rotated Sorted Array II

标签:complex   ble   --   ica   duplicate   problem   order   known   input   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11516050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!