【发布时间】:2021-01-15 01:00:43
【问题描述】:
我正在尝试找出数组中最长的峰值长度。
示例: 数组:[1, 2, 3, 2, 1, 1] 峰值长度:5 (1,2,3,2,1)
我使用以下代码找出数组中最长的峰值:
using namespace std;
int longestPeak(vector<int> array) {
int longestPeak = 0;
int idx = 1;
*`//In the while loop below, if I change the condition to (idx < (array.size() - 1)), it throws a segmentation fault'*
while (idx < int(array.size() - 1)){
bool isPeak = array[idx] > array[idx - 1] and array[idx] > array[idx + 1];
if (!isPeak){
idx += 1;
continue;
}
int leftIdx = idx - 2;
while (leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1])
leftIdx -= 1;
int rightIdx = idx + 2;
while (rightIdx < array.size() and array[rightIdx] < array[rightIdx - 1])
rightIdx += 1;
int currentPeak = rightIdx - leftIdx - 1;
longestPeak = max(currentPeak, longestPeak);
idx = rightIdx;
}
return longestPeak;
}
在下面的第一个 while 循环中,如果我将条件更改为 (idx
请帮助我了解此问题背后的原因。
【问题讨论】:
-
您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定您的程序在哪个点停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?。
-
提供的代码没有给我提供的输入 (
1, 2, 3, 2, 1, 1) 的分段错误。请提供包含触发此崩溃的输入的minimal reproducible example。对于奖励积分,请确定发生崩溃的行以及该点的变量值。 -
另外,提供的代码不会在没有警告的情况下编译。见Why should I always enable compiler warnings?
-
@Peter 在访问
array[leftIdx]之前检查条件leftIdx >= 0。 -
谢谢大家,我通过调试器运行了我的代码。我的问题与作为输入的空数组有关,其中存在 unsigned int 溢出。
标签: c++ arrays data-structures segmentation-fault