【c++】解决大小为一千万的一维数组爆栈方法

把变量放在全局域让它成为全局变量,或者加上static让它成为静态变量,这样变量会放在全局存储区不使用堆或栈空间,不过这都是不推荐的做法。
#include<iostream>
using namespace std;
int main(){
	int a[1000000010];
	int n=0;
	cin>>n;
	int temp=0;
	int max=0; 
	for(int i=0;i<n;i++){
		cin>>temp;
		a[temp]++;
		if(temp>max)max=temp;
	}
	for(int i=0;i<=max;i++){	
		if(a[i]%2==1){
			cout<<i;
			return 0;
		}
	}
}
//这段代码会崩溃

修改:

#include<iostream>
using namespace std;
int sum[10000010];
int main(){
	int n=0;
	cin>>n;
	int temp=0;
	int max=0; 
	for(int i=0;i<10000010;i++){
		sum[i]=0;
	}
	for(int i=0;i<n;i++){
		cin>>temp;
		sum[temp]++;
		if(temp>max)max=temp;
	}
	for(int i=0;i<=max;i++){	
		if(sum[i]%2==1){
			cout<<i;
			return 0;
		}
	}
	return 0;
}
运行正常



猜你喜欢

转载自blog.csdn.net/chenhanxuan1999/article/details/79006383