LeetCode: 数组峰值与谷值问题总结 - Python

LeetCode:数组峰值与谷值问题总结

问题描述:

(1)剑指 Offer 11. 旋转数组的最小数字 , 存在重复元素找最小值
(2)LeetCode: 153. 寻找旋转排序数组中的最小值,元素不相同,找最下值
(3)LeetCode: 154. 寻找旋转排序数组中的最小值 II,存在重复元素,找最小值
(4)LeetCode: 162. 寻找峰值,无序,求峰值
(5)LeetCode: 852. 山脉数组的峰顶索引, 找索引

(1)剑指 Offer 11. 旋转数组的最小数字 Python3实现:

class Solution:
    def minArray(self, numbers: List[int]) -> int:
        low, high = 0, len(numbers) - 1
        while low < high:
            pivot = low + (high - low) // 2
            if numbers[pivot] < numbers[high]:
                high = pivot 
            elif numbers[pivot] > numbers[high]:
                low = pivot + 1
            else:
                high -= 1
        return numbers[low]

(2)LeetCode: 153. 寻找旋转排序数组中的最小值 Python3实现:

class Solution:
    def findMin(self, nums: List[int]) -> int:
        left, right = 0, len(nums) - 1          # 左闭右闭区间,如果用右开区间则不方便判断右值
        while left < right:                     # 循环不变式,如果left == right,则循环结束
            mid = (left + right) >> 1           # 地板除,mid更靠近left
            if nums[mid] > nums[right]:         # 中值 > 右值,最小值在右半边,收缩左边界
                left = mid + 1                  # 因为中值 > 右值,中值肯定不是最小值,左边界可以跨过mid
            elif nums[mid] < nums[right]:       # 明确中值 < 右值,最小值在左半边,收缩右边界
                right = mid                     # 因为中值 < 右值,中值也可能是最小值,右边界只能取到mid处
        return nums[left]                       # 循环结束,left == right,最小值输出nums[left]或nums[right]均可

(3)LeetCode: 154. 寻找旋转排序数组中的最小值 II Python3实现:

class Solution:
    def findMin(self, nums: List[int]) -> int:    
        low, high = 0, len(nums) - 1
        while low < high:
            pivot = low + (high - low) // 2
            if nums[pivot] < nums[high]:
                high = pivot 
            elif nums[pivot] > nums[high]:
                low = pivot + 1
            else:
                high -= 1
        return nums[low]

(4)LeetCode: 162. 寻找峰值 Python3实现:

class Solution:
    def findPeakElement(self, nums):
        low, high = 0, len(nums) - 1
        while low < high: 
            mid = (low + high) // 2
            if nums[mid] > nums[mid + 1]:
                high = mid
            else:
                low = mid + 1
        return low

(5)LeetCode: 852. 山脉数组的峰顶索引 Python3实现:

class Solution:
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        n = len(arr)
        low = 0
        high = n - 1
        while low < high:
            mid = (low + high) // 2
            if arr[mid] > arr[mid+1]:
                high = mid
            else:
                low = mid + 1
        return low

相关参考:
声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。

你可能感兴趣的:(LeetCode,leetcode,python,算法)