LeetCode #153: Find Minimum in Rotated Sorted Array

129 篇文章 0 订阅

Problem Statement

(Source) Suppose a sorted array 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.

You may assume no duplicate exists in the array.

Analysis

Be naive first. One-pass scan can find the minimum element.

class Solution(object):
    def findMin(self, nums):
        return min(nums)

The time complexity is O(n).

Considering that the array is rotated at most once. If the array isn’t rotated at all, then the first element would be the minimum. Otherwise, we can do a linear scan, and the first element that is smaller that its previous element is the minimum.

class Solution(object):
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in xrange(1, len(nums)):
            if nums[i] < nums[i - 1]:
                return nums[i]
        return nums[0]

The time complexity is O(n) at the worst case.

The optimised solution would be using Binary Search.

class Solution(object):
    def findMin(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        lo, hi = 0, len(nums) - 1
        while lo <= hi:
            mid = (lo + hi) >> 1
            if nums[mid] > nums[lo]:
                if nums[lo] <= nums[hi]:
                    return nums[lo]
                else:
                    lo = mid + 1
            elif nums[mid] < nums[lo]:
                hi = mid
            else:
                return min(nums[lo], nums[hi])

The time complexity is O(logn) .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值