Chaithra
Chaithra

Reputation: 1140

Count number of occurrences of array elements

I am stuck in a situation. My problem is to get the most repeated number in an integer array which can have values from 0 to 5,000. The number should at least be repeated n/4 number of times, where n is the array length.

I had a look at extracting at least n/2 times repeated element. But I couldn't modify that to my requirement. Also, since mine is not character array, I can't create an array of 5,000 size to increment the index of the repeated number.

Upvotes: 3

Views: 1656

Answers (1)

unwind
unwind

Reputation: 399703

Here's how I would approach this, I think this makes sense for this kind of problem:

  1. Sort the array (in place), trivial using qsort() if you have it, of course.
  2. Iterate through, keeping a counter that you reset every time the array value changes, and once the counter hits n/4, remember which number it did so for.
  3. Done.

The important thing here is that the sorting makes it trivial to count each element at a time, by grouping all the identical elements together into a single sequence, which makes the counting trivial.

Upvotes: 9

Related Questions