LeetCode #162: Find Peak Element

来源:互联网 发布:form表单怎么提交数据 编辑:程序博客网 时间:2024/04/28 22:47

Problem Statement

(Source) A peak element is an element that is greater than its neighbours.

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:
Your solution should be in logarithmic complexity.

Analysis

Naive O(n) solution.

class Solution(object):    def findPeakElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        n = len(nums)        for i in range(1, n - 1):            num = nums[i]            if num > nums[i-1] and num > nums[i+1]:                return i        return [0, n - 1][nums[0] < nums[n - 1]]

The optimised O(logn) solution would be using Binary Search.

class Solution(object):    def findPeakElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        return self.search(nums, 0, len(nums) - 1)    def search(self, nums, start, end):        if start == end:            return start        elif start + 1 == end:            return [start, end][nums[start] < nums[end]]        else:            mid = (start + end) >> 1            if nums[mid] < nums[mid - 1]:                return self.search(nums, start, mid - 1)            elif nums[mid] < nums[mid + 1]:                return self.search(nums, mid + 1, end)            else:                return mid
0 0
原创粉丝点击