154. Find Minimum in Rotated Sorted Array II

题目描述:

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

Find the minimum element.

The array may contain duplicates.

Example 1:

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

题目翻译

假设按照升序排列的数组在某个关键点上旋转。

找到最小的元素。

该数组可能包含重复项。

示例1:

(例如, 0 1 2 4 5 6 7 可能变为 4 5 6 7 0 1 2).

解题方案

标签: Binary Search

思路:

  • 本题只需用一个变量在遍历给定数组的时候保存前面子序列的最大值即可,因为数组最初为升序,在其旋转后,在旋转点前后两部分仍为升序,所以,在遍历数组过程中,打破升序规律的第一个元素即为要求的最小值。

  • 算法复杂度O(n)。

代码:

class Solution(object):
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sub_large = nums[0]
        for i in nums:
            if i >= sub_large:
                sub_large = i
            else:
                return i
        return nums[0]

参考资料

results matching ""

    No results matching ""