Most common values in an array

后端 未结 4 992
时光说笑
时光说笑 2021-01-14 22:25

How would I go about finding the three most common elements in an array? I am working with an array of length 10,000 with elements = random integer from 0-100.

I was

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 23:30

    You can do it in one loop, but I think you still need that second array.

    I.e. loop over your input array, and each time you see a value, you increment the appropriate index in your 'counter' array. But, also keep 3 'top' indexes (sorted). Each time you increment, check your new value against the value at the top 3 indexes, accounting for the fact that you may be dealing with simply re-ordering your list of 'top' values.

提交回复
热议问题