【LEETCODE】162-Find Peak Element [Python]

来源:互联网 发布:linux dhcp iptables 编辑:程序博客网 时间:2024/05/04 07:19

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

Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.


题意:

一个峰值元素是指它比邻居都大

给一个数组,其中  num[i] ≠ num[i+1],找到它的峰值元素,并返回角标

 num[-1] = num[n] = -∞

如果包含多个峰值,可以只返回其中的一个的角标

注意:

算法应该是对数级的


思路:

用二分法,实现对数复杂度

是为了找极大值,所以,只有当num[mid]小于两边的时候,才会继续向两边寻找大的值

当num[mid]同时大于两边的时候,它就是极大值


参考:

http://bookshadow.com/weblog/2014/12/06/leetcode-find-peak-element/


Python:

class Solution(object):    def findPeakElement(self, nums):        """        :type nums: List[int]        :rtype: int        """                return self.helpsearch(nums,0,len(nums)-1)        def helpsearch(self,nums,start,end):                if start==end:            return start        if end-start==1:            return [end,start][nums[start]>nums[end]]                mid=(start+end)/2        if nums[mid]<nums[mid-1]:            return self.helpsearch(nums,start,mid-1)        if nums[mid]<nums[mid+1]:            return self.helpsearch(nums,mid+1,end)        return mid




0 0
原创粉丝点击