-3

I'm trying to write a program, in which the user gives n numbers and the program has to find out which number is being repeated the most. for example for numbers : 4 5 5 1 3 1 1 7 1 the answer is 1 I'm a beginner by the way, so that's why most of the answers which were already on the site didn't suit me. I'd be very thankful.

Sara
  • 1
  • 1

3 Answers3

2

Use a hashmap (unordered_map) to count the occurrences of the numbers, then search the maximum occurrence count in the hashmap.

midor
  • 5,487
  • 2
  • 23
  • 52
  • 1
    The overhead of hashing is not required here; an `std::map` would suffice. – cdhowie Dec 01 '14 at 20:40
  • Using a std::map increases the algorithmic complexity to O(n log n), whereas using a hashmap is O(n). n O(1) inserts and one O(n) search vs n O(log n) inserts. Have you ensured, that insertion into std::map is faster than into std::unordered_map? – midor Dec 01 '14 at 20:45
0

I think that you can use a priority queue it will holds the elements {1,1,1,1,3,4,5,5,7} and then manipulate the mode from this queue

batuhan
  • 5
  • 3
0

What you probably would want to do is insert the numbers into a std::vector, use std::sort
(in <algorithm>) on it, and loop through it so see which number occurs the most times.

To give you an idea, you may use std::vector<int>::iterator while looping (use auto instead) to point to the beginning + 1 of the vector, then check if the value to which the iterator points is equals to
iterator - 1. If the current value is higher than max value then store it, along with an iterator to that object.

Hope that helps you on the way.

Andreas DM
  • 10,685
  • 6
  • 35
  • 62