162. 寻找峰值

2020-06-30  本文已影响0人  Chiduru

【Description】
峰值元素是指其值大于左右相邻值的元素。

给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。

数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。

你可以假设 nums[-1] = nums[n] = -∞。

示例 1:

输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。
示例 2:

输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5
解释: 你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。
说明:

你的解法应该是 O(logN) 时间复杂度的。

【Idea】
复杂度logN的解法,立即想二分
固定套路了,主要是细节比较多, 注意边界条件。

【Solution】

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 1:
            return 0
        left, right = 0, length-1
        while left < right:       # 限定开区间范围
            idx = (left+right)//2
            l = max(left, idx-1)
            r = min(idx+1, right)
            if (nums[l] < nums[idx] and nums[idx] > nums[r]) or (idx == 0 and nums[idx]>nums[r]) or (idx==length-1 and nums[idx] > nums[l]):         # 左小右小或者边界情况
                return idx
            elif (nums[l] > nums[idx] or idx == right) and nums[idx] > nums[r]:   # 左大右小,左移
                right = idx-1
            elif (nums[l] < nums[idx] or idx == left) and nums[r] > nums[idx]:   # 左小右大,右移
                left = idx+1
            else:   # 左大右大
                if nums[l] >= nums[r]:
                    right = idx-1
                else:
                    left = idx+1
        return left
截屏2020-06-30 上午12.48.03.png
上一篇 下一篇

猜你喜欢

热点阅读