Skip to content

Commit 99d368e

Browse files
add a solution for 347
1 parent cdabae0 commit 99d368e

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/main/java/com/fishercoder/solutions/_347.java

+31
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import java.util.Map.Entry;
88
import java.util.PriorityQueue;
99
import java.util.Queue;
10+
import java.util.TreeMap;
1011

1112
public class _347 {
1213

@@ -74,4 +75,34 @@ public int[] topKFrequent(int[] nums, int k) {
7475
return arr;
7576
}
7677
}
78+
79+
public static class Solution3 {
80+
/**
81+
* Use hashtable and heap, it's averaged at 10 ms on Leetocde.
82+
*/
83+
public int[] topKFrequent(int[] nums, int k) {
84+
Map<Integer, Integer> map = new HashMap<>();
85+
for (int i : nums) {
86+
map.put(i, map.getOrDefault(i, 0) + 1);
87+
}
88+
TreeMap<Integer, List<Integer>> treeMap = new TreeMap<>((a, b) -> b - a);
89+
for (int key : map.keySet()) {
90+
List<Integer> list = treeMap.getOrDefault(map.get(key), new ArrayList<>());
91+
list.add(key);
92+
treeMap.put(map.get(key), list);
93+
}
94+
List<Integer> list = new ArrayList<>();
95+
while (!treeMap.isEmpty()) {
96+
list.addAll(treeMap.pollFirstEntry().getValue());
97+
if (list.size() == k) {
98+
break;
99+
}
100+
}
101+
int[] ans = new int[list.size()];
102+
for (int i = 0; i < list.size(); i++) {
103+
ans[i] = list.get(i);
104+
}
105+
return ans;
106+
}
107+
}
77108
}

src/test/java/com/fishercoder/_347Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@
99
public class _347Test {
1010
private static _347.Solution1 solution1;
1111
private static _347.Solution2 solution2;
12+
private static _347.Solution3 solution3;
1213
private static int[] nums;
1314
private static int[] expected;
1415

1516
@BeforeClass
1617
public static void setup() {
1718
solution1 = new _347.Solution1();
1819
solution2 = new _347.Solution2();
20+
solution3 = new _347.Solution3();
1921
}
2022

2123
@Test
@@ -35,6 +37,7 @@ public void test2() {
3537
nums = new int[]{3, 0, 1, 0};
3638
expected = new int[]{0, 3};
3739
assertArrayEquals(expected, solution2.topKFrequent(nums, 2));
40+
assertArrayEquals(expected, solution3.topKFrequent(nums, 2));
3841
}
3942

4043
@Test

0 commit comments

Comments
 (0)