以下代码是我编写的,适用于大多数情况,但任务如下:
在输入int向量的情况下,需要找到峰和峰的位置,一些示例和条件包括:
arr[] = { 0, 1, 2, 5, 1, 0 }
Then the peak is at position 3 with a value of 5
arr[] = { 1, 2, 2, 2, 1}
If the array plateaus, the peak is the first position of the plateau so in this case, its 2 at
position 1
arr[] = { 1 , 2, 2, 2,3)
This array does not plateau or have a peak so the return value is {}
我不知道我的代码出了什么问题,因为它可以处理我上面提到的示例,但是由于这是一个代码战问题,因此他们使用大量数据输入对其进行了测试,而这正是失败的原因。
#include <iostream>
#include <vector>
using namespace std;
struct PeakData
{
vector<int> pos, peaks;
};
PeakData pick_peaks(vector<int> v)
{
PeakData result;
int max, position, j;
for (int i = 1; i < int(v.size()) - 1; i++)
{
j = i;
if (v[i - 1] < v[i] && v[i] == v[i + 1])
{
while(v[i] == v[j]){
j++;
cout<<v[j]<<endl;
}
cout<<v[j]<<endl;
if(v[j] < v[i]){
position = i;
max = v[i];
result.pos.push_back(position);
result.peaks.push_back(max);
} else continue;
}
if (v[i - 1] < v[i] && v[i + 1] < v[i])
{
position = i;
max = v[i];
result.pos.push_back(position);
result.peaks.push_back(max);
}
}
return result;
}
int main()
{
vector<int> v = {1, 2, 2, 2, 3};
pick_peaks(v);
for (int i = 0; i < pick_peaks(v).peaks.size(); i++)
{
cout << "Peak: " << pick_peaks(v).peaks[i] << endl;
}
for (int i = 0; i < pick_peaks(v).pos.size(); i++)
{
cout << "Position: " << pick_peaks(v).pos[i] << endl;
}
}