我想挑出数组中出现奇数次的元素。我从堆中声明了大小为INT_MAX的数组,并消除了分段错误,但现在它正在进行中。使用相同的算法可以做什么?为什么这段代码超出了时间限制?
/* C++ code to find out the element that occurs odd number of times, given there is only one such element in the array */
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, i;
cin >> n;
int arr[n];
for (i = 0; i < n; i++)
cin >> arr[i];
int* a = new int[INT_MAX]; // declared a dynamic array
fill_n(a, INT_MAX, 0); //initialised to 0
for (i = 0; i < n; i++) {
a[arr[i]]++; // for every particular value, that corresponding index value increases
}
for (i = 0; i < n; i++) {
if(a[arr[i]] % 2 == 1) { //if that corresponding index value is odd, that's the answer
cout << arr[i];
break;
}
}
delete[] a;
return 0;
}
什么是操作系统和编译器? –
你需要找到一种不同的方法。提示:当你对自己的数字进行异或时会发生什么? – NathanOliver
这里有一个更好的问题:你为什么想要分配'INT_MAX'元素? –