Skip to content

Instantly share code, notes, and snippets.

@jones
Created August 29, 2015 07:00
Show Gist options
  • Save jones/331e4a2658785b6ce542 to your computer and use it in GitHub Desktop.
Save jones/331e4a2658785b6ce542 to your computer and use it in GitHub Desktop.
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 e…
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.findPeakRecur(nums, 0, len(nums)-1)
def findPeakRecur(self, nums, lo, hi):
mid = (lo + hi) // 2
if (mid == 0 or nums[mid-1] < nums[mid]) and (mid == len(nums)-1 or nums[mid] > nums[mid+1]):
return mid
elif mid > 0 and nums[mid-1] > nums[mid]:
return self.findPeakRecur(nums, lo, mid-1)
elif mid < len(nums)-1 and nums[mid] < nums[mid+1]:
return self.findPeakRecur(nums, mid+1, hi)
def findPeakElementLinear(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
if (i == 0 or nums[i-1] < nums[i]) and (i == len(nums)-1 or nums[i] > nums[i+1]):
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment