Problems: Find 2 things
- The highest occurrence in an given unsorted integer array
- The element that has the highest occurrence and if there are more than one element satisfy (have the same highest occurrence) the result is the smallest element.
Please solve the problems simple as possible, don't use pointers or any advanced containers like hashtable, pair or map (I'm rather beginner)
For example:
{1, 2, 8, 2, 5, 0, 5}
The answer is 2 and 2 (Element 2
and 5
both occur twice but 2
is the smallest)
Here is the code but it only finds the highest occurrence right.
int A[] = {1, 2, 8, 2, 5, 0, 5};
int N = 7;
int maxCount = 0;
int minMode = 0;
for (int i = 0; i <= N - 1; i++) {
int count = 0;
for (int j = 0; j <= N - 1; j++) {
if (A[i] == A[j])
count++;
}
if (count >= maxCount)
{
maxCount = count;
minMode = A[i];
}
}
cout << maxCount << " " << minMode << endl;