MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / majorityElement

Method majorityElement

java/0229-majority-element-ii.java:7–24  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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 /**

Callers

nothing calls this directly

Calls 4

putMethod · 0.45
getMethod · 0.45
addMethod · 0.45
getKeyMethod · 0.45

Tested by

no test coverage detected