【发布时间】:2017-08-08 13:15:17
【问题描述】:
我想挑选出数组中出现奇数次的元素。我从堆中声明了大小为 INT_MAX 的数组并消除了分段错误,但现在它给出了 tle。使用相同的算法可以做什么?
/* 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;
}
【问题讨论】:
-
什么是操作系统和编译器?
-
您需要找到不同的方法。提示:当你将一个数字与自身异或时会发生什么?
-
@Muskan 如果不适合物理内存,则用零填充 8 GB 可能需要很多秒。
-
如果你知道一个数字恰好出现奇数次,你可以只用两个整数变量来解决这个问题。稍微改变一下你的观点(微妙的提示)。
-
尝试使用
std::map<element, frequency>。如果该元素存在于地图中,则增加频率;否则插入一个新元素。最后,遍历地图,打印具有奇数频率的元素。