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.
Note:
题目要求时间复杂度为O(logn)~所以可以用二分搜索来完成~找到一个local maximum
Your solution should be in logarithmic complexity.
给定一个数组,返回其中一个峰点值~峰点值就是比左右相邻的元素都大的一个元素~最直观的一种解法是线性查找,代码如下,不过时间复杂度是O(n)~
class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
if num is None: return None
for i in xrange(1, len(num)):
if num[i] < num[i - 1]:
return i - 1
return len(num) - 1
题目要求时间复杂度为O(logn)~所以可以用二分搜索来完成~找到一个local maximum
class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
if num is None: return None
l, r = 0, len(num) - 1
while l < r:
mid = l + (r - l) / 2
if num[mid] > num[mid + 1]:
r = mid
else:
l = mid + 1
return l