Skip to content

Instantly share code, notes, and snippets.

@yiling-chen
Created February 5, 2018 16:47
Show Gist options
  • Save yiling-chen/9358a6fd58366b1f72dd23bef00f2cd5 to your computer and use it in GitHub Desktop.
Save yiling-chen/9358a6fd58366b1f72dd23bef00f2cd5 to your computer and use it in GitHub Desktop.
int majorityElement(vector<int>& nums) {
unordered_map<int, int> counter;
for (auto num : nums) {
if (counter.count(num))
counter[num] += 1;
else
counter[num] = 1;
}
int max_count = -1;
int majority_num;
for (auto p : counter) {
if (p.second > max_count) {
max_count = p.second;
majority_num = p.first;
}
}
return majority_num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment