moonlightshadow123
6/21/2017 - 2:45 PM

162. Find Peak Element

  1. Find Peak Element
class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 1:
            return 0
        start = -1
        end = len(nums)
        while start < end:
            mid = (start + end) / 2
            leftVal = self.getVal(nums, mid-1)
            rightVal = self.getVal(nums, mid+1)
            if leftVal <= nums[mid] and nums[mid] >= rightVal:
                return mid
            elif leftVal > nums[mid]:
                end = mid
            else:
                start = mid
    def getVal(self, nums, index):
        if index == -1 or index == len(nums):
            return -float('inf')
        else:
            return nums[index]

https://leetcode.com/problems/find-peak-element/#/description

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.