其实只要改一下if条件即可
#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};
Solution solution;
int peakValue = 0;
int valleyValue = 0;
int A = 4; // 限制值
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;
}
我实测没问题(忽略编码问题)
PS E:\> g++ main.cpp -o main
PS E:\> ./main
鏈?鍚庝竴涓尝宄板?间负: 16
鏈?鍚庝竴涓尝璋峰?间负: 8
请按任意键继续. . .
PS E:\>
|