First solution utilizes a hashmap and then does the due diligience of adding the appropriate values that appear more than n/3 times Runtime O(n) : Space O(n)
(int[] nums)
| 5 | * Runtime O(n) : Space O(n) |
| 6 | */ |
| 7 | public List<Integer> majorityElement(int[] nums) { |
| 8 | List<Integer> res = new ArrayList<>(); |
| 9 | Map<Integer, Integer> map = new HashMap<>(); |
| 10 | for (int i = 0; i < nums.length; i++) { |
| 11 | if (map.containsKey(nums[i])) |
| 12 | map.put(nums[i], map.get(nums[i]) + 1); |
| 13 | else |
| 14 | map.put(nums[i], 1); |
| 15 | } |
| 16 | |
| 17 | for (Map.Entry<Integer, Integer> entry: map.entrySet()) { |
| 18 | int potentialCandidate = entry.getValue(); |
| 19 | if (potentialCandidate > nums.length / 3) |
| 20 | res.add(entry.getKey()); |
| 21 | } |
| 22 | |
| 23 | return res; |
| 24 | } |
| 25 | |
| 26 | |
| 27 | /** |