【发布时间】:2017-04-30 15:29:34
【问题描述】:
我正在编写代码来检查 zig-zag 数组(其 3 个连续元素不是按递增或递减顺序排列的数组)并返回要删除的最小元素数以使其成为 zig-zag。但是我遇到了大型数组的分段错误。
#include <bits/stdc++.h>
using namespace std;
int minimumDeletions(vector < int > a,int n){
int i,j;
j=n;
for(i=0;i<n;i++){
if(a[i]>a[i+1]){
if(a[i+1]>a[i+2]){
a.erase(a.begin()+(i+2));
i--;
n--;
continue;
}
else{continue;}
}
if(a[i]<a[i+1]){
if(a[i+1]<a[i+2]){
a.erase(a.begin()+(i+2));
i--;
n--;
}
else{continue;}
}
}
j=j-n;
return j;
}
int main() {
int n;
cin >> n;
vector<int> a(n);
for(int a_i = 0; a_i < n; a_i++){
cin >> a[a_i];
}
// Return the minimum number of elements to delete to make the array zigzag
int result = minimumDeletions(a,n);
cout << result << endl;
return 0;
}
【问题讨论】:
-
我建议你开始使用迭代器,忘记基于索引的遍历。它会解决很多错误。
标签: c++ arrays vector dynamic fault