|
| 1 | +package array; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/** |
| 9 | + * Description: https://leetcode.com/problems/majority-element-ii |
| 10 | + * Difficulty: Medium |
| 11 | + */ |
| 12 | +public class MajorityElement2 { |
| 13 | + |
| 14 | + /** |
| 15 | + * Time complexity: O(n) |
| 16 | + * Space complexity: O(1) |
| 17 | + */ |
| 18 | + public List<Integer> majorityElementViaMooreAlgo(int[] nums) { |
| 19 | + int count1 = 0; |
| 20 | + int count2 = 0; |
| 21 | + |
| 22 | + // there can only be 2 elements that appear more than n/3 times |
| 23 | + int candidate1 = nums[0]; |
| 24 | + int candidate2 = nums[0]; |
| 25 | + |
| 26 | + for (int num : nums) { |
| 27 | + if (candidate1 == num) { |
| 28 | + count1++; |
| 29 | + } else if (candidate2 == num) { |
| 30 | + count2++; |
| 31 | + } else if (count1 == 0) { |
| 32 | + candidate1 = num; |
| 33 | + count1++; |
| 34 | + } else if (count2 == 0) { |
| 35 | + candidate2 = num; |
| 36 | + count2++; |
| 37 | + } else { |
| 38 | + count1--; |
| 39 | + count2--; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + // second pass to check, if candidates really appear more than n/3 times |
| 44 | + return checkCandidatesFrequency(nums, candidate1, candidate2); |
| 45 | + } |
| 46 | + |
| 47 | + private static List<Integer> checkCandidatesFrequency(int[] nums, int candidate1, int candidate2) { |
| 48 | + int count1 = 0; |
| 49 | + int count2 = 0; |
| 50 | + |
| 51 | + for (int num : nums) { |
| 52 | + if (num == candidate1) { |
| 53 | + count1++; |
| 54 | + } else if (num == candidate2) { |
| 55 | + count2++; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + int n = nums.length / 3; |
| 60 | + List<Integer> result = new ArrayList<>(); |
| 61 | + |
| 62 | + if (count1 > n) result.add(candidate1); |
| 63 | + if (count2 > n) result.add(candidate2); |
| 64 | + |
| 65 | + return result; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Time complexity: O(n) |
| 70 | + * Space complexity: O(m) |
| 71 | + */ |
| 72 | + public List<Integer> majorityElementViaMap(int[] nums) { |
| 73 | + Map<Integer, Integer> freqMap = new HashMap<>(); |
| 74 | + for (int num : nums) { |
| 75 | + freqMap.merge(num, 1, Integer::sum); |
| 76 | + } |
| 77 | + |
| 78 | + List<Integer> result = new ArrayList<>(); |
| 79 | + int n = nums.length / 3; |
| 80 | + for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) { |
| 81 | + if (entry.getValue() > n) result.add(entry.getKey()); |
| 82 | + } |
| 83 | + |
| 84 | + return result; |
| 85 | + } |
| 86 | +} |
0 commit comments