This algorithm can be used for leetcode 229 and leetcode 169.
The algorithm is called Boyer-Moore majority vote algorithm.
A blog for this algorithm can be found here.
This algorithm can solve the following problem: Given an unordered array of size n
of int, find all the elements that appear more than floor(n / k)
times, with O(k - 1)
space complexity and O(n * (k - 1))
time complexity.
The idea is:
- First, we allocate a vector of
k - 1
elements calledvals
. This is because we can have at mostk - 1
elements that satisfy the condition that it appears more thanfloor(n / k)
times. We assign unique numbers tovals
. We also allocate vectorcounts
of sizek - 1
to record the number of times each value appears.counts
is initialized to all zero. - Then, for each
num
innums
, we check allk - 1
values.- If
num
is the same as one of theval
, we increase itscount
. - If
num
is not the same as any of theval
, but we find aval
withcount == 0
, we replace thatval
withnum
, and set itscount
back to1
. - If
num
is not the same as any of theval
, and for all theval
s, we havecount > 0
, we then decreacecount
for all theval
s.
- If
- Finally, we go through all the
k - 1
values we recorded. For eachval
, we find its actual appearance time innums
, if this count satisfynew_count > floor(n / k)
, then,val
is a solution. If not, we discard thisval
.
The c++ implementation is as following:
1 | vector<int> majorityElements(const vector<int>& nums, int k) { |