各位老师,c++如何查找队列波峰波谷,从左到右第一个到最后1个都算,(加一个阈值A=4,波峰波谷的差值>4)?查找了很多案例,加阈值A=4后,出来结果都不正确?那位老师有正确的方法?谢谢了,下面是源码,出来的值有问题[C++] 纯文本查看 复制代码 #include <iostream>
#include <vector>
class Solution
{
public:
void findPeakValley(const std::vector<int> &nums, int &peakValue, int &valleyValue, int A)
{
int cur = 0, pre = 0;
for (int i = 1; i < nums.size(); i++)
{
int cur = nums[i] - nums[i - 1];
if (cur > 0 && pre <= 0 && nums[i - 1] <= valleyValue + A)
{
valleyValue = nums[i - 1];
}
else if (cur < 0 && pre >= 0 && nums[i - 1] >= peakValue - A)
{
peakValue = nums[i - 1];
}
pre = cur;
}
// 处理最后一个元素
if (nums.size() >= 2)
{
if (nums[nums.size() - 1] > nums[nums.size() - 2] && nums[nums.size() - 1] >= peakValue - A)
{
peakValue = nums[nums.size() - 1];
}
else if (nums[nums.size() - 1] < nums[nums.size() - 2] && nums[nums.size() - 1] <= valleyValue + A)
{
valleyValue = nums[nums.size() - 1];
}
}
}
};
int main()
{
std::vector<int> nums = { 1, 17, 13, 5, 10, 15, 11, 16, 8, 11, 9, 14 };
Solution solution;
int peakValue = 0;
int valleyValue = 0;
int A = 5; // 限制值
solution.findPeakValley(nums, peakValue, valleyValue, A);
if (peakValue != 0)
{
std::cout << "最后一个波峰值为: " << peakValue << std::endl;
}
else
{
std::cout << "未找到波峰" << std::endl;
}
if (valleyValue != 0)
{
std::cout << "最后一个波谷值为: " << valleyValue << std::endl;
}
else
{
std::cout << "未找到波谷" << std::endl;
}
system("pause");
return 0;
} |