题目:
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;
}
};
本文介绍了一个算法问题——在给定的数组中找到一个峰值元素并返回其索引。峰值元素定义为大于其邻居的元素。文章提供了C++实现的代码示例,并解释了如何通过比较相邻元素来高效地找到峰值。
371

被折叠的 条评论
为什么被折叠?



