Leetcode 153

假设按照升序排序的数组在预先未知的某个点上进行了旋转。

( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

请找出其中最小的元素。

你可以假设数组中不存在重复元素。

示例 1:

输入: [3,4,5,1,2]
输出: 1

示例 2:

输入: [4,5,6,7,0,1,2]
输出: 0

方法:

首先遍历列表如果发生旋转,就找到变换的位置,如果没有发生旋转直接返回列表的第一个元素即可

AC代码如下:

class Solution:
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        length = len(nums)
        if length == 1 or length == 0:
            return nums[0]

        i = 1
        while i < length:
            if nums[i] <= nums[i-1]:
                return nums[i]
            i += 1
        return nums[0]

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/85598901