Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created January 27, 2019 23:05
Show Gist options
  • Save ttsugriy/a10d1c9f0cc9a9d2e5784e8a6699477b to your computer and use it in GitHub Desktop.
Save ttsugriy/a10d1c9f0cc9a9d2e5784e8a6699477b to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int count1 = 0;
int count2 = 0;
int candidate1 = -1;
int candidate2 = -1;
for (int num : nums) {
if (num == candidate1) {
count1 += 1;
} else if (num == candidate2) {
count2 += 1;
} else if (count1 == 0) {
candidate1 = num;
count1 = 1;
} else if (count2 == 0) {
candidate2 = num;
count2 = 1;
} else {
count1 -= 1;
count2 -= 1;
}
}
// get actual total counts
count1 = 0;
count2 = 0;
for (int num : nums) {
count1 += num == candidate1;
count2 += num == candidate2;
}
vector<int> top_elements;
if (count1 * 3 > nums.size()) top_elements.push_back(candidate1);
if (count2 * 3 > nums.size()) top_elements.push_back(candidate2);
return top_elements;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment