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

Commit8ac18b1

Browse files
authored
Merge pull requestneetcode-gh#367 from bubbleship/main
Update 347-Top-K-Frequent-Elements.java
2 parents5c3d533 +d805404 commit8ac18b1

File tree

1 file changed

+59
-1
lines changed

1 file changed

+59
-1
lines changed

‎java/347-Top-K-Frequent-Elements.java

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
classSolution {
1+
classSolution1 {
2+
/**
3+
* Time Complexity: O(nlog(k))
4+
* Space Complexity: O(n)
5+
*/
26
publicint[]topKFrequent(int[]nums,intk) {
37
int[]arr =newint[k];
48
HashMap<Integer,Integer>map =newHashMap<>();
@@ -17,3 +21,57 @@ public int[] topKFrequent(int[] nums, int k) {
1721
returnarr;
1822
}
1923
}
24+
25+
classSolution2 {
26+
/**
27+
* Time Complexity: O(n)
28+
* Space Complexity: O(n)
29+
*/
30+
publicint[]topKFrequent(int[]numbers,intk) {
31+
HashMap<Integer,Integer>map =newHashMap<>();
32+
for (intnumber :numbers)
33+
map.put(number,map.getOrDefault(number,0) +1);
34+
35+
intsize =map.size();
36+
int[]keys =newint[size];
37+
inti =0;
38+
for (intkey :map.keySet())
39+
keys[i++] =key;
40+
41+
select(keys,map,0,size -1,size -k);
42+
returnArrays.copyOfRange(keys,size -k,size);
43+
}
44+
45+
// Modified implementation of Hoare's selection algorithm:
46+
47+
privatevoidselect(int[]keys,Map<Integer,Integer>map,intleft,intright,intkSmallest) {
48+
while (left !=right) {
49+
intpivot =partition(keys,map,left,right, (left +right) /2);
50+
51+
if (kSmallest ==pivot)return;
52+
53+
if (kSmallest <pivot)right =pivot -1;
54+
elseleft =pivot +1;
55+
}
56+
}
57+
58+
privateintpartition(int[]keys,Map<Integer,Integer>map,intleft,intright,intpivot) {
59+
intpivotValue =map.get(keys[pivot]);
60+
swap(keys,pivot,right);
61+
intindex =left;
62+
63+
for (inti =left;i <=right;i++)
64+
if (map.get(keys[i]) <pivotValue) {
65+
swap(keys,i,index);
66+
index++;
67+
}
68+
swap(keys,right,index);
69+
returnindex;
70+
}
71+
72+
privatevoidswap(int[]array,inti1,inti2) {
73+
inttemp =array[i1];
74+
array[i1] =array[i2];
75+
array[i2] =temp;
76+
}
77+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp