[NeetCode 150] Find Minimum in Rotated Sorted Array

Find Minimum in Rotated Sorted Array

You are given an array of length n which was originally sorted in ascending order. It has now been rotated between 1 and n times. For example, the array nums = [1,2,3,4,5,6] might become:

[3,4,5,6,1,2] if it was rotated 4 times.
[1,2,3,4,5,6] if it was rotated 6 times.
Notice that rotating the array 4 times moves the last four elements of the array to the beginning. Rotating the array 6 times produces the original array.

Assuming all elements in the rotated sorted array nums are unique, return the minimum element of this array.

A solution that runs in O(n) time is trivial, can you write an algorithm that runs in O(log n) time?

Example 1:

Input: nums = [3,4,5,6,1,2]

Output: 1

Example 2:

Input: nums = [4,5,0,1,2,3]

Output: 0

Example 3:

Input: nums = [4,5,6,7]

Output: 4

Constraints:

1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000

Solution

Referring to Find Target in Rotated Sorted Array, we can use the same method. However, this problem can be seen as a simplified version that we only need to judge whether nums[mid] > nums[ri] to see where the minimum is.

Code

Just simplify the binary search function in Find Target in Rotated Sorted Array

class Solution:
    def findMin(self, nums: List[int]) -> int:
        le = 0
        ri = len(nums)-1
        ans = nums[0]
        while le <= ri:
            mid = (le+ri)//2
            print(le, mid, ri)
            if nums[le] <= nums[mid]:
                if nums[le] > nums[ri]:
                    ans = min(ans, nums[ri])
                    le = mid+1
                else:
                    ans = min(ans, nums[le])
                    ri = mid-1
            else:
                ans = min(ans, nums[mid])
                ri = mid-1
        return ans

Most simplified:

class Solution:
    def findMin(self, nums: List[int]) -> int:
        start , end = 0, len(nums) - 1 
        curr_min = float("inf")
        
        while start  <  end :
            mid = start + (end - start ) // 2
            curr_min = min(curr_min,nums[mid])
            
            # right has the min 
            if nums[mid] > nums[end]:
                start = mid + 1
                
            # left has the  min 
            else:
                end = mid - 1 
                
        return min(curr_min,nums[start])
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值