1. 程式人生 > >leetcode【162】Find Peak Element

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.

 

沒啥好說的

class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        if len(nums) == 1:
            return 0
        for i in range(1,len(nums)-1):
            if nums[i-1] < nums[i] & nums[i] > nums[i+1]:
                return i
        for i in range(0, len(nums) - 1):
            if nums[i] > nums[i+1]:
                return i
        for i in range(0, len(nums)):
            if nums[len(nums)-1] > nums[len(nums)-2]:
                return len(nums)-1

真的很簡單,難道有更快的?

我看到有的人用二分,水平可以,就是沒必要,找到第一個就可以了好麼,要那麼複雜幹嘛

但是,二分法是很值得講一講的

其實我們只需要找到連續的三個數,中間那個比兩邊大即可。用二分的話,就是從中間開始找第一個峰值。

我們找到一個數,然後向左向右縮小範圍,直到left和right兩個指標重合。

如果大家理解不了,可以自己手動紙上畫一畫

二分真的是一種很棒的思想

class Solution(object):
    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]:
                right = mid 
            elif  nums[mid] < nums[mid + 1]:
                left = mid + 1
        return right