From ea3686b3d2b5a569473b0ba8a2c005698a2a5fc8 Mon Sep 17 00:00:00 2001 From: Abhay kaushik <78193848+abhay57@users.noreply.github.com> Date: Fri, 28 Oct 2022 17:11:17 +0530 Subject: [PATCH] Create Answer15.cpp --- Answer15.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Answer15.cpp diff --git a/Answer15.cpp b/Answer15.cpp new file mode 100644 index 0000000..218a95c --- /dev/null +++ b/Answer15.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +class solution{ + + int findMajority(vector &arr) + { + int n = arr.size(), maj_index = 0, count = 1; + for (int i = 1; i < n; i++) { + if (arr[maj_index] == arr[i]) + count++; + else + count--; + if (count == 0) { + maj_index = i; + count = 1; + } + } + + int res = arr[maj_index]; + count = 0; + for (int i = 0; i < n; i++){ + if (arr[i] == res) + count++; + } + + if (count > n / 2) + return res; + + return -1; + } + +};