How to count distinct values in a list in linear time?

前端 未结 3 989
旧巷少年郎
旧巷少年郎 2020-12-20 16:55

I can think of sorting them and then going over each element one by one but this is nlogn. Is there a linear method to count distinct elements in a list?

3条回答
  •  半阙折子戏
    2020-12-20 16:58

    Add every element of the list to a HashSet and then check the size (cardinality) of the HashSet, which is the number of distinct values in the list.

提交回复
热议问题