#include<bits/stdc++.h> using namespace std;
const int N=1e4+10; int n; boolean flag; int res; int a[N];

int main() { cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; }

for(int i=0;i<n;i++)     {
    for(int j=i;j<n;j++)         {
        sort(a+i,a+j+1);
        flag=true;
        for(int k=i+1;k<=j;k++)             {
        	if(a[k]!=a[k-1]+1)
        	flag=false;
		}
		if(flag)
			res++;
    }
}

cout<<res<<endl;

return 0;

}

这段代码输入 4 3 2 4 1 时正确答案应该是 7 但是这段代码有问题,怎么修改内容:这段代码的问题在于每次排序的时间复杂度是 O(nlogn),而且排序的范围也很大,没有必要每次都排序整个数组。可以通过记录当前区间的最大值和最小值来判断是否是连续的区间。修改后的代码如下:

#include<bits/stdc++.h> using namespace std;
const int N=1e4+10; int n; boolean flag; int res; int a[N];

int main() { cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; }

for(int i=0;i<n;i++)     {
    int mx = a[i], mn = a[i]; //记录当前区间的最大值和最小值
    for(int j=i;j<n;j++)         {
        mx = max(mx, a[j]);
        mn = min(mn, a[j]);
        if(mx - mn == j - i && j != i) //如果当前区间是连续的,则计数器加1
            res++;
    }
}

cout<<res<<endl;

return 0;

}

C++ 代码优化:寻找连续区间计数

原文地址: https://www.cveoy.top/t/topic/m6Ln 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录