#include <bits/stdc++.h>
using namespace std;
int majorityElement(vector<int> v) {
//size of the given array:
int n = v.size();
int cnt = 0; // count
int el; // Element
//applying the algorithm:
for (int i = 0; i < n; i++) {
if (cnt == 0) {
cnt = 1;
el = v[i];
}
else if (el == v[i]) cnt++;
else cnt--;
}
//checking if the stored element
// is the majority element:
int cnt1 = 0;
for (int i = 0; i < n; i++) {
if (v[i] == el) cnt1++;
}
if (cnt1 > (n / 2)) return el;
return -1;
}
int main()
{
vector<int> arr = {2, 2, 1, 1, 1, 2, 2};
int ans = majorityElement(arr);
cout << "The majority element is: " << ans << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFqb3JpdHlFbGVtZW50KHZlY3RvcjxpbnQ+IHYpIHsKCiAgICAvL3NpemUgb2YgdGhlIGdpdmVuIGFycmF5OgogICAgaW50IG4gPSB2LnNpemUoKTsKICAgIGludCBjbnQgPSAwOyAvLyBjb3VudAogICAgaW50IGVsOyAvLyBFbGVtZW50CgogICAgLy9hcHBseWluZyB0aGUgYWxnb3JpdGhtOgogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBuOyBpKyspIHsKICAgICAgICBpZiAoY250ID09IDApIHsKICAgICAgICAgICAgY250ID0gMTsKICAgICAgICAgICAgZWwgPSB2W2ldOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChlbCA9PSB2W2ldKSBjbnQrKzsKICAgICAgICBlbHNlIGNudC0tOwogICAgfQoKICAgIC8vY2hlY2tpbmcgaWYgdGhlIHN0b3JlZCBlbGVtZW50CiAgICAvLyBpcyB0aGUgbWFqb3JpdHkgZWxlbWVudDoKICAgIGludCBjbnQxID0gMDsKICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbjsgaSsrKSB7CiAgICAgICAgaWYgKHZbaV0gPT0gZWwpIGNudDErKzsKICAgIH0KCiAgICBpZiAoY250MSA+IChuIC8gMikpIHJldHVybiBlbDsKICAgIHJldHVybiAtMTsKfQoKaW50IG1haW4oKQp7CiAgICB2ZWN0b3I8aW50PiBhcnIgPSB7MiwgMiwgMSwgMSwgMSwgMiwgMn07CiAgICBpbnQgYW5zID0gbWFqb3JpdHlFbGVtZW50KGFycik7CiAgICBjb3V0IDw8ICJUaGUgbWFqb3JpdHkgZWxlbWVudCBpczogIiA8PCBhbnMgPDwgZW5kbDsKICAgIHJldHVybiAwOwp9Cg==