-
Notifications
You must be signed in to change notification settings - Fork 16
/
top-three-repeated.cpp
83 lines (68 loc) · 2.21 KB
/
top-three-repeated.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// C++ Program to Find the top three repeated numbers
#include <bits/stdc++.h>
using namespace std;
/* Function to print top three repeated numbers */
void top3Repeated(int arr[], int n)
{
// There should be atleast two elements
if (n < 3) {
cout << "Invalid Input";
return;
}
// Count Frequency of each element
unordered_map<int, int> fre;
for (int i = 0; i < n; i++)
fre[arr[i]]++;
// Initialize first value of each variable
// of Pair type is INT_MIN
pair<int, int> x, y, z;
x.first = y.first = z.first = INT_MIN;
for (auto curr : fre) {
// If frequency of current element
// is not zero and greater than
// frequency of first largest element
if (curr.second > x.first) {
// Update second and third largest
z = y;
y = x;
// Modify values of x Number
x.first = curr.second;
x.second = curr.first;
}
// If frequency of current element is
// not zero and frequency of current
// element is less than frequency of
// first largest element, but greater
// than y element
else if (curr.second > y.first) {
// Modify values of third largest
z = y;
// Modify values of second largest
y.first = curr.second;
y.second = curr.first;
}
// If frequency of current element
// is not zero and frequency of
// current element is less than
// frequency of first element and
// second largest, but greater than
// third largest.
else if (curr.second > z.first) {
// Modify values of z Number
z.first = curr.second;
z.second = curr.first;
}
}
cout << "Three largest elements are "
<< x.second << " " << y.second
<< " " << z.second;
}
// Driver's Code
int main()
{
int arr[] = { 3, 4, 2, 3, 16, 3, 15,
16, 15, 15, 16, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
top3Repeated(arr, n);
return 0;
}