[LeetCode][JavaScript]Find Minimum in Rotated Sorted Array II
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.
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
接着上一题 Find Minimum in Rotated Sorted Array
还是二分查找,加上寻找重复数字的代码,最坏情况下的复杂度是O(n).
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var findMin = function(nums) { 6 var start = 0, end = nums.length - 1, middle; 7 while(start < end){ 8 if(nums[start] < nums[end]) 9 return nums[start]; 10 while(nums[start] === nums[start + 1]) 11 start++; 12 while(nums[end] === nums[end - 1]) 13 end--; 14 middle = (start + end) >> 1; 15 if(nums[start] <= nums[middle]) 16 start = middle + 1; 17 else 18 end = middle; 19 } 20 return nums[start]; 21 };