[LeetCode]Find Peak Element

题目描述:

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:

Your solution should be in logarithmic complexity.

题目大意:

“峰值元素”是指值大于邻居的元素

输入一个数组num[i] ≠ num[i+1],找到一个峰值元素并返回其下标。

数组可能包含多个峰值,这种情况下返回其中任意一个即可。

可以假设num[-1] = num[n] = -∞(开始元素的左侧和末尾元素的右侧均为负无穷大)

例如,数组[1, 2, 3, 1]中,3是峰值元素,你的函数应该返回下标2。

注意:

解决方案最好为对数复杂度。

解题思路:

Brute Force暴力枚举,线性复杂度 O(n)

二分法,对数复杂度O(log n)

Python代码:

二分法O(log n)版本:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findPeakElement(self, num):
        size = len(num)
        return self.search(num, 0, size - 1)
    
    def search(self, num, 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]:
            return self.search(num, start, mid - 1)
        if num[mid] < num[mid + 1]:
            return self.search(num, mid + 1, end)
        return mid

线性暴力枚举O(n)版本:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findPeakElement(self, num):
        size = len(num)
        for x in range(1, size - 1):
            if num[x] > num[x - 1] and num[x] > num[x + 1]:
                return x
        return [0, size - 1][num[0] < num[size - 1]]

 

本文链接:http://bookshadow.com/weblog/2014/12/06/leetcode-find-peak-element/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论