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?
这个题目是聊天题, 只需要告诉面试官, 最坏的情况下会是 O(n) , T: O(n) worse case, like 1 1 1 1 1.. 0 1 1, 就是在很多1里面有一个0, 那么我们肯定至少需要n-1次.
Code
class Solution: def findMin(self, nums): ## Solution T: O(n) worse case, like 1 1 1 1 1.. 0 1 1, 就是在很多1里面有一个0, 那么我们肯定至少需要n-1次 if not nums: return 0 ans = nums[0] for num in nums: if num < ans: ans = num return ans
扫描二维码关注公众号,回复:
2975497 查看本文章