为什么此代码超出了时间限制?

时间:2017-08-08 13:15:17

标签: c++ time

我想挑选出数组中出现奇数次数的元素。我从堆中声明了大小为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;       
}

1 个答案:

答案 0 :(得分:3)

此:

int* a = new int[INT_MAX];  // declared a dynamic array

将分配20亿个整数,即8 GB的存储空间。您将随机访问哪个。您的系统可能很难分配那么多存储空间,即使可以,也可能无法在任何时间限制内实际读写这么多内存。

你问了

  

使用相同的算法可以做些什么?

无。该算法不足,不能以实用的方式使用。您将需要一个不同的算法。