[BaekJoon] 10989번 - 수 정렬하기 3 [Java][C++]
[BaekJoon] 10989번 - 수 정렬하기 3 [Java][C++]
1. 아이디어
주어진 N개의 수를 정렬하는 문제로 수의 개수가 최대 10,000,000개로 매우 많은데 수의 범위는 작다는 점에서 카운팅 소트를 활용하면 효율적으로 해결할 수 있다.
1부터 최대 10,000까지 원소들의 등장 횟수를 카운팅한 다음 각 숫자의 등장 횟수만큼 출력하는 방식으로 해결했다.
2. 코드
1. 풀이 [Java]
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 MX = 10000;
static int[] cnt = new int[1 + MX];
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 <= MX; i++) {
for (int j = 1; j <= cnt[i]; j++) {
sb.append(i).append("\n");
}
}
System.out.println(sb);
}
}
2. 풀이 [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
#include <bits/stdc++.h>
using namespace std;
const int MX = 10000;
int cnt[1 + MX];
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 <= MX; i++) {
for (int j = 1; j <= cnt[i]; j++) {
cout << i << '\n';
}
}
}
3. 디버깅
없음.
4. 참고
없음.
This post is licensed under CC BY 4.0 by the author.