Home > Backend Development > C++ > Array elements that appear multiple times?

Array elements that appear multiple times?

WBOY
Release: 2023-08-26 15:57:06
forward
932 people have browsed it

Array elements that appear multiple times?

Here we will see a problem. We have an array. Our task is to find those elements whose frequency is greater than 1. Suppose the elements are {1, 5, 2, 5, 3, 1, 5, 2, 7}. Here 1 appears 2 times, 5 appears 3 times, 2 appears 3 times, and the others only appear once. So the output will be {1, 5, 2}

Algorithm

moreFreq(arr, n)

Begin
   define map with int type key and int type value
   for each element e in arr, do
      increase map.key(arr).value
   done
   for each key check whether the value is more than 1, then print the key
End
Copy after login

Example

#include <iostream>
#include <map>
using namespace std;
void moreFreq(int arr[], int n){
   map<int, int> freq_map;
   for(int i = 0; i<n; i++){
      freq_map[arr[i]]++; //increase the frequency
   }
   for (auto it = freq_map.begin(); it != freq_map.end(); it++) {
      if (it->second > 1)
         cout << it->first << " ";
   }
}
int main() {
   int arr[] = {1, 5, 2, 5, 3, 1, 5, 2, 7};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Frequency more than one: ";
   moreFreq(arr, n);
}
Copy after login

Output

Frequency more than one: 1 2 5
Copy after login

The above is the detailed content of Array elements that appear multiple times?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template