[LeetCode] 162. Find Peak Element

题:

题目

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.

Note:

Your solution should be in logarithmic complexity.

思路

题目大意

找出 i,使得 nums[i-1] < nums[i] > nums[i+1]。若 nums[j] 越界那么返回 -inf。
所以 i不止一个。但 返回一个符合要求的 下标即可。
时间复杂度最好 O(logn)

解题思路

方法一

从左到右遍历 nums ,将其与左右元素比较,输出符合要求的 i 。时间复杂度为O(n)。

方法二、三

参考:https://www.jianshu.com/p/308ad7e4f824

code

方法一

class Solution:
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            if i ==0:
                leftnum = float('-inf')
            else:
                leftnum = nums[i-1]
            if i ==len(nums)-1:
                rightnum = float('-inf')
            else:
                rightnum = nums[i+1]
            if nums[i]> leftnum and nums[i]> rightnum :
                return i

方法二

class Solution:
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)-1):
            if nums[i] > nums[i+1]:
                return i
        return len(nums)-1

方法三

class Solution:
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left = 0 
        right = len(nums) - 1
        while left<right:
            mid = (left + right) //2
            if nums[mid] < nums[mid + 1]:
                left = mid + 1
            else:
                right = mid
        return left

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82913054
今日推荐