1. 程式人生 > >[LeetCode] 162. Find Peak Element

[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)。

方法二、三

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