How to find to the Max Repeated value in an array?

How to find to the Max Repeated value in an array in shortest time. The Value inside the array are random, but the size of the array is fixed.

Is there is any way to find repeated value during the value is storing in the Array.

e.g long Array[] = {31,42,31,36,43,23,367,377,42, 334,222,644,3434,65,32,42,88};
Maximum Repeat = 3
Maximum Repeated Value = 42
Hi,
Can you let us know what you have done ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
    long Array[] = {31,42,31,36,43,23,367,377,42, 334,222,644,3434,65,32,42,88};
    long SIZE(sizeof(Array) / sizeof(Array[0]));

    std::sort(Array, Array + SIZE);

    long mostRepeatedValue(0);
    long countRepeats(0);

    for(long* it(Array); it != Array + SIZE; ++it)
    {
        std::pair <long* , long*> distance(std::equal_range(Array, Array + SIZE, *it));
        if (std::distance(distance.first, distance.second) >= countRepeats)
        {
            countRepeats = std::distance(distance.first, distance.second);
            mostRepeatedValue = *it;
        }
    }

    std::cout << "mostRepeatedValue " << mostRepeatedValue << "\ncountRepeats " << countRepeats << '\n';

    return 0;
}
New version, it is more easy to debug and it's faster
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
    long Array[] = {31,42,31,36,43,23,367,377,42, 334,222,644,3434,65,32,42,88};
    long SIZE(sizeof(Array) / sizeof(Array[0]));

    long* end(Array + SIZE);
    long* begin(Array);
    std::sort(begin, end);

    long mostRepeatedValue(0);
    long countRepeats(0);

    long* it(begin);
    while(it != end)
    {
        std::pair <long* , long*> distance(std::equal_range(begin, end, *it));
        long currentValueRepeats(std::distance(distance.first, distance.second));
        if (currentValueRepeats > countRepeats)
        {
            countRepeats = currentValueRepeats;
            mostRepeatedValue = *it;
        }
        it = distance.second;
    }

    std::cout << "mostRepeatedValue " << mostRepeatedValue << "\ncountRepeats " << countRepeats << '\n';

    return 0;
}
Last edited on
Topic archived. No new replies allowed.