zoukankan      html  css  js  c++  java
  • LeetCode-Find Minimum in Rotated Sorted Array I & II

    153. Find Minimum in Rotated Sorted Array

    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.

    Solution

    # binary search
    class Solution(object):
        def findMin(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            low = 0
            high = len(nums) - 1
            while low < high:
                mid = (low + high)/2
                if nums[mid] < nums[high]:
                    high = mid
                elif nums[mid] > nums[high]:
                    low = mid + 1
            return nums[low]
    

    154. Find Minimum in Rotated Sorted Array II

    Follow up for "Find Minimum in Rotated Sorted Array":
    What if duplicates are allowed?
    Would this affect the run-time complexity? How and why?

    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.

    The array may contain duplicates.

    Solution

    class Solution(object):
        def findMin(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            low = 0
            high = len(nums) - 1
            while low < high:
                mid = low + (high - low)/2
                if nums[mid] > nums[high]:
                    low = mid + 1
                elif nums[mid] < nums[high]:
                    high = mid
                else:
                    high -= 1 
            return nums[low]
    
  • 相关阅读:
    内置常量
    python100练
    python之禅
    Django
    pymsql入门
    jQuery事件
    数据库(索引)
    算法基础知识
    数据库(查询专项)
    数据库(所有人都坐下!这是基本操作!)
  • 原文地址:https://www.cnblogs.com/binwone/p/6086133.html
Copyright © 2011-2022 走看看