LeetCode 题解(137): Find Peak Element

来源:互联网 发布:如何提高淘宝店铺的销量 编辑:程序博客网 时间:2024/06/10 04:12

题目:

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.


题解:

规定要Logn复杂度,所以只能Binary Search。思路是: 如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。

C++版:

class Solution {public:    int findPeakElement(vector<int>& nums) {        int l = 0, r = nums.size() - 1;        while(l <= r) {            if(l == r)                return l;            int mid = (l + r) / 2;            if(nums[mid] > nums[mid + 1])                r = mid;            else                l = mid + 1;        }    }};

Java版:

public class Solution {    public int findPeakElement(int[] nums) {        int l = 0, r = nums.length - 1;        while(l <= r) {            if(l == r)                return l;            int mid = (l + r) / 2;            if(nums[mid] > nums[mid + 1])                r = mid;            else                l = mid + 1;        }        return 0;    }}

Python版:

class Solution:    # @param nums, an integer[]    # @return an integer    def findPeakElement(self, nums):        if len(nums) == 1:            return 0                l, r = 0, len(nums) - 1        while l <= r:            if l == r:                return l            mid = (l + r) / 2            if nums[mid] > nums[mid+1]:                r = mid            else:                l = mid + 1


0 0