Question
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
Solution
For finding the majority elements, there is a very famous algorithm Boyer–Moore majority vote algorithm. But the original algorithm is for finding the majority number that appears more than ⌊ n/2 ⌋ times. So we need to modify the algorithm to find numbers that appears more than n/3. Use 2 counter to keep tracking of 2 candidate numbers.
For every number in array,
- Check if it is one of the two candidate numbers.
- Check if its’ counter is 0, if counter is 0, update candidate number and set counter to 1.
- If it is not satisfy either of the above conditions. Decrement the counter by 1.
After the first round loop, we have two “majority” numbers but we don’t know if they appears more than n/3 time. So we start another loop to count the occurrence time.
Finally, if the occurrence time is more than n/3, add it to result set.
1 | public class Solution { |