Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nacho4d/4d90e9315509a9ed0a33 to your computer and use it in GitHub Desktop.
Save nacho4d/4d90e9315509a9ed0a33 to your computer and use it in GitHub Desktop.
Majority element
// https://oj.leetcode.com/problems/majority-element/
// Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
// You may assume that the array is non-empty and the majority element always exist in the array.
class Solution {
public:
// Hash table
int majorityElement_hashtable(vector<int> &num) {
std::map <int, int> table;
for (int n : num) {
auto it = table.find(n);
table[n] = it == table.end() ? 1 : (it->second + 1);
}
int threshold = static_cast<int>(num.size() / 2);
int res = -1;
for (auto const & kv : table) {
if (kv.second > threshold) {
threshold = kv.second;
res = kv.first;
}
}
return res;
}
// Voting algorithm
// http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html
int majorityElement_voting(vector<int> &num) {
int counter = 0;
int candidate = -1;
for (int n : num) {
if (counter == 0) {
candidate = n;
++counter;
} else {
if (candidate == n) {
++counter;
} else {
--counter;
}
}
}
return candidate;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment