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
publicclassSolution {publicList<Integer> majorityElement(int[] nums) {int a =0;int b =0;int m =0;int n =0;int size =nums.length;if (size <=0) {returnnewArrayList<>(); }for (int i =0; i <nums.length; i++) {if (a == nums[i]) { m++; } elseif (b == nums[i]) { n++; } elseif (m ==0) { a = nums[i]; m =1; } elseif (n ==0) { b = nums[i]; n =1; } else { m--; n--; } }List<Integer> result =newArrayList<>();if (m !=0&&verify(nums, a, size)) {result.add(a); }if (n !=0&&verify(nums, b, size)&& b != a) {result.add(b); }return result; }privatebooleanverify(int[] nums,int candidate,int size) {int count =0;for (int num : nums) {if (num == candidate) { count++; } }return (double) count > (double) size /3; }}