Find the most repeated elements in an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.