Skip to content
This repository has been archived by the owner on May 29, 2024. It is now read-only.

add-algorithm-that-counts-the-occurences-of-numbers #1307

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions algorithms/CPlusPlus/Arrays/number-occurences-counter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
Counts the occurence of each number in the given array outputs it.
Using an unordered_map to store the count of each number.
Time complexity O(n)
*/



#include <iostream>
#include <unordered_map>
#include <vector>

void countOccurrences(const std::vector<int>& arr){
std::unordered_map<int, int> count;

for(int n: arr){
count[n]++;
}

for(const auto& pair : count){
std::cout << "The number: " << pair.first<< " occurs " <<pair.second<< " times." << std::endl;
}
}

int main() {

std::vector<int> myArray = {12, 4, 12, 23, 1, 1, 12, 4, 5};
countOccurrences(myArray);

return 0;
}