From bd7d57c0c6fb196b3ccd0dde385f2aa3cd21a074 Mon Sep 17 00:00:00 2001 From: varshaaCodes <91754632+varshaaCodes@users.noreply.github.com> Date: Sat, 16 Oct 2021 19:33:58 +0530 Subject: [PATCH] Added cpp code for Question 16 --- Answer16.cpp | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Answer16.cpp diff --git a/Answer16.cpp b/Answer16.cpp new file mode 100644 index 0000000..aa4f067 --- /dev/null +++ b/Answer16.cpp @@ -0,0 +1,71 @@ +//cpp code for Majority Element(>n/3 times) +#include +using namespace std; + +int appearsNBy3(int arr[], int n) +{ + int count1 = 0, count2 = 0; + int first=INT_MAX , second=INT_MAX ; + + for (int i = 0; i < n; i++) { + + + if (first == arr[i]) + count1++; + + // if this element is previously seen, + // increment count2. + else if (second == arr[i]) + count2++; + + else if (count1 == 0) { + count1++; + first = arr[i]; + } + + else if (count2 == 0) { + count2++; + second = arr[i]; + } + + + else { + count1--; + count2--; + } + } + + count1 = 0; + count2 = 0; + + + for (int i = 0; i < n; i++) { + if (arr[i] == first) + count1++; + + else if (arr[i] == second) + count2++; + } + + if (count1 > n / 3) + return first; + + if (count2 > n / 3) + return second; + + return -1; +} + +int main() +{ + int n; + cin>>n; + int arr[n]; + for(int i=0;i>arr[i]; + } + + cout << appearsNBy3(arr, n) << endl; + return 0; +}