本文主要是介绍LeetCode *** 162. 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.
分析:
心急想快点把写过的题提交。。结果一直WA...果然心急吃不来热豆腐。。
代码:
class Solution {
public:int findPeakElement(vector<int>& nums) {int size=nums.size();int pre=INT_MIN,next=INT_MIN;for(int i=0;i<size-1;++i){if(nums[i]>nums[i+1]&&nums[i]>pre)return i;if(nums[i]>nums[i+1]){i++;pre=nums[i+1];}else pre=nums[i];}if(nums[size-1]>nums[size-2])return size-1;return 0;}
};
这篇关于LeetCode *** 162. Find Peak Element的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!