Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit99d368e

Browse files
add a solution for 347
1 parentcdabae0 commit99d368e

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
importjava.util.Map.Entry;
88
importjava.util.PriorityQueue;
99
importjava.util.Queue;
10+
importjava.util.TreeMap;
1011

1112
publicclass_347 {
1213

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

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@
99
publicclass_347Test {
1010
privatestatic_347.Solution1solution1;
1111
privatestatic_347.Solution2solution2;
12+
privatestatic_347.Solution3solution3;
1213
privatestaticint[]nums;
1314
privatestaticint[]expected;
1415

1516
@BeforeClass
1617
publicstaticvoidsetup() {
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 =newint[]{3,0,1,0};
3638
expected =newint[]{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)

[8]ページ先頭

©2009-2025 Movatter.jp