配列内で奇数回発生する要素を選択したいと考えています。私はヒープから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;
}
OSとコンパイラとは何ですか? –
あなたは別のアプローチを見つける必要があります。ヒント:あなたが自分自身の数字をxorするとどうなりますか? – NathanOliver
ここではより良い質問があります:なぜあなたは 'INT_MAX'要素を割り当てたいと思いますか? –