leetcode 【 Find Peak Element 】python 实现

题目

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.

代码

分别用递归和非递归两种方法实现。

非递归版代码:oj测试通过 Runtime: 55 ms

 class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
if len(num) == 1 :
return 0
if len(num) == 2 :
return [0,1][num[0] < num[1]]
start = 0
end = len(num)-1
while start <= end:
if start == end:
return start
if start+1 == end:
return [start,end][num[start] < num[end]]
mid = (start+end)/2
if num[mid] < num[mid-1]:
#start = 0
end = mid -1
elif num[mid] < num[mid+1]:
start = mid+1
#end = len(num)-1
else:
return mid

递归代码:oj测试通过 Runtime: 51 ms

 class Solution:
# @param num, a list of integer
# @return an integer
def find(self,num,start,end):
if start == end :
return start
if end == start + 1:
if num[start] < num[end] :
return end
else:
return start
mid = (start+end)/2
if num[mid] < num[mid-1] :
return self.find(num, start, mid-1)
if num[mid] < num[mid+1] :
return self.find(num, mid, end)
return mid def findPeakElement(self, num):
if len(num) == 1:
return 0
return self.find(num, 0, len(num)-1)

思路

二分查找思路升级版。参照如下两篇日志的思路:

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

http://blog.csdn.net/u010367506/article/details/41943309

这道题在理解题意上需要注意就是默认这个数组的虚头和虚尾都是负无穷,并且这个数组不存在相等的两个元素,这样就一定能够找到题中描述的peak point.

上一篇:Leetcode#169. Majority Element(求众数)


下一篇:MATLAB读写Excel文件中的数据