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:
At most has two elements in the result, can use two counter to record occurrence. Then calculate if match the condition.
public ListmajorityElement(int[] nums) { List result = new ArrayList<>(); if(nums.length==0) return result; int n1 = nums[0]; int n2 = 0; int count1 = 1; int count2 = 0; for(int i=1;i nums.length/3) result.add(n1); if(n1 == n2) return result; if(count2>nums.length/3) result.add(n2); return result; }