Counting unique element in large array

前端 未结 8 717
执念已碎
执念已碎 2021-02-03 15:33

One of my colleagues was asked this question in an interview.

Given a huge array which stores unsigned int. Length of array is 100000000. Find the effective

8条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 16:07

    If the range of the int values is limited, then you may allocate an array, which serves to count the occurrences for each possible value. Then you just iterate through your huge array and increment the counters.

    foreach x in huge_array {
       counter[x]++;
    }
    

    Thus you find the solution in linear time (O(n)), but at the expense of memory consumption. That is, if your ints span the whole range allowed by 32-bit ints, you would need to allocate an array of 4G ints, which is impractical...

提交回复
热议问题