我的代码1.0
#include<iostream>
using namespace std;
int count(int *a, int n) {
int result = n + 1;
for (int i = 2; i < n; ++i) //测试不同区间长度
for (int j = 0; j + i <= n; ++j) {
//max - min + 1 = n 则为连续区间
int min = a[j], max = a[j];
for (int k = 1; k < i; ++k) {
if (a[j + k] < min)
min = a[j + k];
if (a[j + k] > max)
max = a[j + k];
}
if (max - min + 1 == i)
++result;
}
return result;
}
int main() {
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
cout << count(a, n);
return 0;
}
直接超时
我的代码2.0
#include<iostream>
using namespace std;
int count(int *a, int n) {
int result = 0;
for (int i = 0; i < n - 1; ++i) { //为了i+1保持一致,i < n - 1,最后再++result
int min, max, j, k = i; //i为区间左端点,j为右端点,k为检查点
if (a[i] < a[i + 1]) {
min = a[i];
max = a[i + 1];
} else {
min = a[i + 1];
max = a[i];
}
++result;
j = i + max - min; //区间长度=max-min
while (j < n) {
for (; k <= j; ++k) {
if (a[k] < min) {
min = a[k++];
break;
}
if (a[k] > max) {
max = a[k++];
break;
}
}
if (j == i + max - min) { //区间里每个数都在min到max之间说明成立
++result;
++j;
} else
j = i + max - min;
}
}
++result;
return result;
}
int main() {
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
cout << count(a, n);
return 0;
}
看了网上的代码后进行精简3.0
#include<iostream>
using namespace std;
int count(int *a, int n) {
int result = 0;
for (int i = 0; i < n; ++i) {
int min = a[i], max = a[i], j = i, k = i; //i为区间左端点,j为右端点,k为检查点
while (j < n) { //区间长度=max-min
for (; k <= j; ++k) {
if (a[k] < min) {
min = a[k++];
break;
}
if (a[k] > max) {
max = a[k++];
break;
}
}
if (j == i + max - min) { //区间里每个数都在min到max之间说明成立
++result;
++j;
} else
j = i + max - min;
}
}
return result;
}
int main() {
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
cout << count(a, n);
return 0;
}