Find the element with the most repeated times in the array, and the element with the array repetition times
1. Problem Description
For example: array a = {, 5,}, each element 2, 3, 7, 8 appears once, 1 appears twice, 5 appears four times, the most repeated element is 5.
2. methods and ideas 2.1 use space for time and Index
Define an arrayint cnt[MAX]
And Initialize all its elements to 0. Then traverse array a and executecnt[a[i]]++
Operation. Finally, find the maximum number in the cnt array, which is the maximum number of repetitions.
The sample code is as follows:
// Use space for time, index method int MaxFreq_index (int a [], int n) {int I, j; int max = a [0]; // obtain the maximum value, for (I = 1; I <n; I ++) if (a [I]> max) max = a [I]; int * cnt = new int [max]; for (I = 0; I <max; I ++) cnt [I] = 0; max = 0; for (I = 0; I <n; I ++) {if (++ cnt [a [I]> = cnt [max]) {max = a [I] ;}} return max ;}
2.2 map ing method
Map key-value pairs are used to record the number of occurrences of elements. Keys are elements and values are the number of occurrences of keys. The time complexity is o (n ).
#include <map>...int MaxFreq_map(int a[],int n){ map<int,int> mp; int i,maxfreqNum=0; for(i = 0; i < n; i++) if( ++mp[a[i]] >= mp[0] ) maxfreqNum = a[i]; return maxfreqNum;}