[BaekJoon] #10989 - 수 정렬하기 3 [Java][C++]
[BaekJoon] #10989 - 수 정렬하기 3 [Java][C++]
1. 아이디어
주어진 $N$개의 수를 정렬하는 문제로 수의 개수가 최대 $10{,}000{,}000$개로 매우 많은데 수의 범위는 작다는 점에서 카운팅 소트를 활용하면 효율적으로 해결할 수 있다.
1부터 최대 10,000까지 원소들의 등장 횟수를 카운팅한 다음 각 숫자의 등장 횟수만큼 출력하는 방식으로 해결했다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N + K)$ | $O(K)$ |
($N$ = 입력값 n, $K$ = 값의 범위)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.*;
public class Main {
static final int MAX = 10001;
static int[] cnt = new int[MAX];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
while (n-- > 0) {
cnt[Integer.parseInt(br.readLine())]++;
}
for (int i = 1; i < MAX; i++) {
for (int j = 1; j <= cnt[i]; j++) {
sb.append(i).append("\n");
}
}
System.out.println(sb);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;
const int MAX = 10001;
int cnt[MAX];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
while (n--) {
int x;
cin >> x;
cnt[x]++;
}
for (int i = 1; i < MAX; i++) {
for (int j = 1; j <= cnt[i]; j++) {
cout << i << '\n';
}
}
}
This post is licensed under CC BY 4.0 by the author.