154. Find Minimum in Rotated Sorted Array II
problem description
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:
Example 2:
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?
algorithm thought
上一题的拓展版本,可以有重复数字,我们需要处理的也是重复数字。每次对于最左边的数字,如果和右边的数字重复,就将left++。之后的处理基本和上一题一样了
这里需要理解的是,如果数组有序,直接返回left,否组数组肯定是两段有序,mid肯定在两段中的一段。mid和left相比,如果mid >= left,left-mid这段就是有序的,最小值肯定不再中间,mid < left,mid-right这段是有序的,最小值肯定不再这段
code
algorithm analysis
上一题时间复杂度是O(lgn),这里加入了重复数组计算,如果所有数字都是重复的,那么处理重复数字的时间复杂度会达到O(n),所以这里时间复杂度是O(n)
Last updated