Find Peak Element

来源:互联网 发布:淘宝包邮软件 编辑:程序博客网 时间:2024/05/17 05:07

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.

click to show spoilers.

解析:

遍历每个元素,找左右大大小关系


代码:

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




0 0