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 - 1elements calledvals. This is because we can have at mostk - 1elements that satisfy the condition that it appears more thanfloor(n / k)times. We assign unique numbers tovals. We also allocate vectorcountsof sizek - 1to record the number of times each value appears.countsis initialized to all zero. - Then, for each
numinnums, we check allk - 1values.- If
numis the same as one of theval, we increase itscount. - If
numis not the same as any of theval, but we find avalwithcount == 0, we replace thatvalwithnum, and set itscountback to1. - If
numis not the same as any of theval, and for all thevals, we havecount > 0, we then decreacecountfor all thevals.
- If
- Finally, we go through all the
k - 1values we recorded. For eachval, we find its actual appearance time innums, if this count satisfynew_count > floor(n / k), then,valis a solution. If not, we discard thisval.
The c++ implementation is as following:
1 | vector<int> majorityElements(const vector<int>& nums, int k) { |