1. Description of the problem
For example: Array a={2,3,1,5,5,5,5,7,8,1}, elements 2, 3, 7, 8 appear 1 times, 1 appear two times, 5 appear 4 times, the most repeated element is 5.
2. Methods and ideas 2.1 with space change time, index method
Defines an array int cnt[MAX] that initializes all its elements to 0. The array A is then traversed to perform the cnt[a[i]]++ operation. Finally, the largest number is found in the CNT array, and the corresponding number is the most repeated number.
The code examples are as follows:
//With space change time, index methodintMaxfreq_index (intA[],intN) {intI,j;int Max= a[0];//Find the maximum value to allocate the count array space for(i =1; I < n; i++)if(A[i] >Max)Max= A[i];int*cnt = newint[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 Mapping method
Use map key-value pairs to record the number of occurrences of an element, the key is an element, and the value is the number of occurrences of the key. The time complexity is O (n).
#include <map>...int MaxFreq_map(int a[],int n){ map<int,int> mp; int i,maxfreqNum=0; for0; i < n; i++) if( ++mp[a[i]] >= mp[0] ) maxfreqNum = a[i]; return maxfreqNum;}
Find the most repeated elements in an array