[백준] 10989번 - 수 정렬하기 3 [Java][C++]
[백준] 10989번 - 수 정렬하기 3 [Java][C++]
1. 문제 풀이
주어진 $N$ 개의 수를 정렬하는 문제로 수의 개수가 최대 $10,000,000$ 개로 매우 많은데 수의 범위는 작다는 점에서 카운팅 배열을 활용하면 효율적으로 해결할 수 있다.
$1$ 부터 최대 $10000$ 까지 원소들의 등장 횟수를 카운팅한 다음 각 숫자의 등장 횟수만큼 출력하는 방식으로 해결했다.
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
26
import java.io.*;
public class Main {
static final int MAX = 10_000;
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());
int[] cntArr = new int[1 + MAX];
for (int i = 0; i < N; i++) {
cntArr[Integer.parseInt(br.readLine())]++;
}
for (int i = 1; i <= MAX; i++) {
for (int j = 1; j <= cntArr[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;
constexpr int MAX = 10000;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> cntArr(1 + MAX);
for (int i = 0; i < n; i++) {
int x;
cin >> x;
cntArr[x]++;
}
for (int i = 1; i <= MAX; i++) {
for (int j = 1; j <= cntArr[i]; j++) {
cout << i << '\n';
}
}
}
3. 풀이 정보
1. 정렬 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 1552 ms | 336860 KB | 666 B |
2. 정렬 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 1532 ms | 2180 KB | 431 B |
This post is licensed under CC BY 4.0 by the author.