【leetcode】162. Find Peak Element

来源:互联网 发布:阿里云栖大会地址 编辑:程序博客网 时间:2024/05/17 07:15

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.

解题思路:
当前值与周围相邻的比较,需要注意边界问题,如果只有一个元素,则其本身就是peak
如果是递增序列,则最后一个是peak
如果是递减序列,则第一个是peak
python:

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

C++第一次尝试刷题:nums.size()可以直接取形参数组的长度。

class Solution {public:    int findPeakElement(vector<int>& nums) {        if (nums.size()==1){            return 0;        }        int i = 0;        int len = nums.size();        for(i = 1;i<len-1; i++){            if (nums[i]>nums[i-1] && nums[i]>nums[i+1])            {                return i;            }        }        if (nums[len-1] > nums[0]){            return len-1;        }        else{            return 0;        }        return 0;    }};
0 0