【LEETCODE】162-Find Peak Element [Python]
2016-01-08 19:45
501 查看
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
= -∞.
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
= -∞
如果包含多个峰值,可以只返回其中的一个的角标
注意:
算法应该是对数级的
思路:
用二分法,实现对数复杂度
是为了找极大值,所以,只有当num[mid]小于两边的时候,才会继续向两边寻找大的值
当num[mid]同时大于两边的时候,它就是极大值
参考: http://bookshadow.com/weblog/2014/12/06/leetcode-find-peak-element/
Python:
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
= -∞.
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
= -∞
如果包含多个峰值,可以只返回其中的一个的角标
注意:
算法应该是对数级的
思路:
用二分法,实现对数复杂度
是为了找极大值,所以,只有当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
相关文章推荐
- Python字符串操作
- python通过外部参数发送邮件
- python--列表生成式--8
- 菜鸟学python(5) while语句
- Python+Selenium实现股票板块数据模拟抓取
- python 爬虫(二)
- Python 数据库客户端 DB-API
- Python 日期,时间和函数的使用
- python 浅拷贝(shallow copy) 深拷贝(deep copy)
- 矩阵等式 matrix identity(numpy仿真)
- 一个有用的python装饰器 -- 为执行程序加锁
- python3.5[No module named 'encodings']报错
- python实现base64加密/解密界面化小工具
- python 例子2: 利用 unittest 实现自动加载并执行它定义的方法
- python 例子: 实现动态加载类,并自动执行它定义的函数
- python random
- Python xml文件解析
- python---骰子游戏
- python 修正系统时差
- windows下python安装paramiko