leetcode 154. Find Minimum in Rotated Sorted Array II

xiaoxiao2021-02-28  78


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.

(这道题用二分查找需谨慎,注意以下几个测试用例):

int[] nums=new int[]{1,3,3}; int[] nums=new int[]{3,1,1}; int[] nums=new int[]{3,1,3}; int[] nums=new int[]{3,3,1,3};我对于这道题二分查找的方法百思不得其解,只能用了最平凡的方法。 public int findMin(int[] nums) { if(nums.length==1){ return nums[0]; } for(int i=0;i<nums.length-1;i++){ if(nums[i+1]<nums[i]){ return nums[i+1]; } } return nums[0]; }大神就是用的二分查找的方法。

需要注意的是,这道题二分查找只能在 > 或者 < 时 二分。 当 = 时,会不清楚到底在左边还是右边,因此只能将 high-- 来缩小范围。

class Solution { public: int findMin(vector<int> &num) { int lo = 0; int hi = num.size() - 1; int mid = 0; while(lo < hi) { mid = lo + (hi - lo) / 2; if (num[mid] > num[hi]) { lo = mid + 1; } else if (num[mid] < num[hi]) { hi = mid; } else { // when num[mid] and num[hi] are same hi--; } } return num[lo]; } }; When num[mid] == num[hi], we couldn't sure the position of minimum in mid's left or right, so just let upper bound reduce one.

转载请注明原文地址: https://www.6miu.com/read-54745.html

最新回复(0)