Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find which numbers appears most in a vector

Tags:

c++

vector

I have some numbers stored in a std::vector<int>. I want to find which number appears most in the vector.

e.g. in the vector

1 3 4 3 4 2 1 3 2 3

the element that occurs the most is 3.

Is there any algorithm (STL or whatever) that does this ?

like image 925
VaioIsBorn Avatar asked Mar 21 '10 22:03

VaioIsBorn


People also ask

How do you find the highest number in a vector?

You can use max_element to get the maximum value in vector. The max_element returns an iterator to largest value in the range, or last if the range is empty. As an iterator is like pointers (or you can say pointer is a form of iterator), you can use a * before it to get the value.

How do you find the most common element in a vector in R?

To find the most frequent factor value in an R data frame column, we can use names function with which. max function after creating the table for the particular column. This might be required while doing factorial analysis and we want to know which factor occurs the most.


1 Answers

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.

like image 147
sepp2k Avatar answered Sep 20 '22 18:09

sepp2k