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

前端 未结 3 991
旧巷少年郎
旧巷少年郎 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 17:10

    You can adapt this extremely cool O(n)-time and O(1)-space in-place algorithm for removing duplicates to the task of counting distinct values -- simply count the number of values equal to the sentinel value in a final O(n) pass, and subtract that from the size of the list.

提交回复
热议问题