Skip to content

Commit 1901b6e

Browse files
committed
top k frequent elements
1 parent e4613f7 commit 1901b6e

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
Problem 347 : Top K Frequent Elements
3+
Summary :
4+
- Map을 통해 숫자의 중복 횟수를 구한다.
5+
- 배열을 통해, 중복 횟수를 인덱스로 해당 숫자를 연결 리스트를 통해 값을 저장한다.
6+
- 중복 횟수를 저장한 배열에서 마지막 인덱스부터 for문을 돌리면서 k개까지 리턴 배열에 숫자를 저장한다.
7+
- 제약 조건에서 응답이 유일하다는 것을 보장하고 있으므로, 개수가 부족하거나, 중복에 대해서는 고려하지 않아도 된다.
8+
- 정렬을 이용하면 최소한 시간복잡도가 O(NlogN)이지만 해당 방법은 O(N)이 가능하다.
9+
10+
*/
11+
12+
class Solution {
13+
class Node {
14+
int num;
15+
Node next;
16+
public Node(int n){
17+
num = n;
18+
}
19+
}
20+
class NodeList {
21+
Node head;
22+
Node tail;
23+
24+
public NodeList() {
25+
}
26+
27+
public void add(Node node){
28+
if(head == null){
29+
head = node;
30+
tail = node;
31+
return;
32+
}
33+
34+
tail.next = node;
35+
tail = tail.next;
36+
}
37+
38+
public boolean empty() {
39+
return head == null;
40+
}
41+
}
42+
43+
public int[] topKFrequent(int[] nums, int k) {
44+
NodeList[] list = new NodeList[nums.length+1];
45+
int[] result = new int[k];
46+
Map<Integer, Integer> map= new HashMap<>();
47+
48+
for(int i=0; i < list.length; i++) {
49+
list[i] = new NodeList();
50+
}
51+
52+
for(int i = 0; i < nums.length; i++) {
53+
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
54+
}
55+
56+
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
57+
list[entry.getValue()].add(new Node(entry.getKey()));
58+
}
59+
60+
int idx = 0;
61+
for(int i=list.length-1; (i >= 0) && (idx < k); i--) {
62+
if(!list[i].empty()) {
63+
Node head = list[i].head;
64+
while(head != null) {
65+
result[idx] = head.num;
66+
head = head.next;
67+
idx++;
68+
}
69+
}
70+
}
71+
return result;
72+
}
73+
}

0 commit comments

Comments
 (0)