LeetCode 162. Find Peak Element

来源:互联网 发布:地砖 铺装 软件 编辑:程序博客网 时间:2024/04/29 21:42

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.


题目大意:

找出元素b,假设b元素前面的元素是a,后面的元素是c。则元素b满则b>ab>c。则返回元素b的下标。如果存在多个,则返回任意一个即可。我们把第一个元素的前面看作负无穷,最后一个元素的后一个也看作负无穷。


题目代码:

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


原创粉丝点击