From 99f34f4d3abdf35949dbd3fc9b7adf87471994cd Mon Sep 17 00:00:00 2001 From: HimadriPathak Date: Sun, 17 Oct 2021 11:58:07 +0530 Subject: [PATCH] added answer 16 in c++ language --- Answer16.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Answer16.cpp diff --git a/Answer16.cpp b/Answer16.cpp new file mode 100644 index 0000000..7f9aea0 --- /dev/null +++ b/Answer16.cpp @@ -0,0 +1,58 @@ +#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++; + + 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 arr[] = { 1, 2, 3, 1, 1 }; + int n = sizeof(arr) / sizeof(arr[0]); + cout << appearsNBy3(arr, n) << endl; + return 0; +} \ No newline at end of file