From 568d81debdaa4ac807f5a347b35af4a4874503e7 Mon Sep 17 00:00:00 2001 From: Raunak Somani <77135253+raunak321321@users.noreply.github.com> Date: Thu, 23 Sep 2021 01:12:41 +0530 Subject: [PATCH] chore(CPlusPlus): add elements appear thrice (#477) --- .../Arrays/Elements_appears_thrice.cpp | 48 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 3 +- 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 algorithms/CPlusPlus/Arrays/Elements_appears_thrice.cpp diff --git a/algorithms/CPlusPlus/Arrays/Elements_appears_thrice.cpp b/algorithms/CPlusPlus/Arrays/Elements_appears_thrice.cpp new file mode 100644 index 00000000..6a7cf813 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/Elements_appears_thrice.cpp @@ -0,0 +1,48 @@ +// elements with frequency = (3) in a given array +//time complexity : O(n) || space complexity : O(1) + +#include +#include + +using namespace std; + +int main() +{ // main function begins here + int size; + cout << "Enter the size of the array : "; + cin >> size; + + int *arr = new int[size]; + map mp; + + for (int i = 0; i < size; i++) + { + cout << "Enter " << i << " th element of array : "; + cin >> arr[i]; + mp[arr[i]]++; // this simply stores the frequency of each element in this array + } + + map::iterator it; // this is an iterator which is used to iterate all over the map + + int count = 0; + + for (it = mp.begin(); it != mp.end(); it++) + { + if ((*it).second == 3) // checks whether element frequency is 3 or not + { + count++; // just check how many elements are there which have frequency 3 + if (count == 1) + { + cout << "The elements whose frequency is 3 are: "; + } + cout << (*it).first << " "; // print the element which satisfy the above condition + } + } + if (count == 0) + { + cout << "There is no elements in this array whose frequency is 3."; // special print if there is no such elements + } + + cout << endl; + return 0; +} \ No newline at end of file diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 79ec0149..184faf19 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -14,7 +14,8 @@ 10. [Quick Selection](Arrays/quick-select.cpp) 11. [Remove Duplicates](Arrays/remove-duplicates.cpp) 12. [Leaders In The Array](Arrays/leaders-in-array.cpp) -13. [Maximum Difference](Arrays/maximum-difference.cpp) +13. [Elements appear thrice In The Array](Arrays/Elements_appears_thrice.cpp) +14. [Maximum Difference](Arrays/maximum-difference.cpp) ## Dynamic-Programming