代码改变世界

[LeetCode] 154. Find Minimum in Rotated Sorted Array II_Hard

2018-08-31 07:01  Johnson_强生仔仔  阅读(183)  评论(0编辑  收藏  举报

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:

这个题目是聊天题, 只需要告诉面试官, 最坏的情况下会是 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