Find which numbers appears most in a vector

后端 未结 6 2057
一个人的身影
一个人的身影 2021-01-19 02:57

I have some numbers stored in a vector . I want to find which number appears most in the vector.

Is there any easy/fast algorithm (STL or whatever) that does this ?<

6条回答
  •  遥遥无期
    2021-01-19 03:42

    Sort it, then iterate through it and keep a counter that you increment when the current number is the same as the previous number and reset to 0 otherwise. Also keep track of what was the highest value of the counter thus far and what the current number was when that value was reached. This solution is O(n log n) (because of the sort).

    Alternatively you can use a hashmap from int to int (or if you know the numbers are within a limited range, you could just use an array) and iterate over the vector, increasing the_hashmap[current_number] by 1 for each number. Afterwards iterate through the hashmap to find its largest value (and the key belonging to it). This requires a hashmap datastructure though (unless you can use arrays which will also be faster), which isn't part of STL.

提交回复
热议问题