I am trying to determine the most frequent character in a vector that has chars as its elements.
I am thinking of doing this:
- looping through the vector and creating a map, where a key would be a unique char found in the vector. The corresponding value would be the integer count of the frequency of that char.
- After I have gone through all elements in the vector, the map will
contain all character frequencies. Thus I will then have to find
which key had the highest value and therefore determine the most
frequent character in the vector.
This seems quite convoluted though, thus I was wondering if someone could suggest if this method would be considered ‘acceptable’ in terms of performance/good coding
Can this be done in a better way?
If you are only using regular ascii characters, you can make the solution a bit faster – instead of using a map, use an array of size 256 and count the occurrences of the character with a given code ‘x’ in the array cell
count[x]. This will remove an logarithm(256) from your solution and thus will make it a bit faster. I do not think much more can be done with respect to optimization of this algorithm.