제출 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
int max = 0;
for(int i = 0; i < N; i++) {
int value = Integer.parseInt(br.readLine());
arr[i] = value;
max = Math.max(max, value);
}
int[] count = new int[max + 1];
// 1. 각 숫자의 개수를 세기
for(int num : arr) {
count[num]++;
}
// 2. 누적합으로 변환하여 정렬된 위치를 결정
for(int i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
// 3. 정렬된 배열으 만들기(역순으로 처리하여 안정 정렬 유지)
int[] output = new int[N];
for(int i = arr.length - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for(int num : output) {
bw.write(num + "\n");
}
br.close();
bw.flush();
bw.close();
}
}
문제 의도
- 메모리 제한
'알고리즘' 카테고리의 다른 글
프로그래머스 42747번 | H-Index 문제 풀이 (Java) (0) | 2025.03.13 |
---|---|
고급 정렬 알고리즘 구현: 카운팅 정렬 (Java) (1) | 2025.03.10 |
고급 정렬 알고리즘 구현: 병합 정렬 (Java) (0) | 2025.03.06 |
백준 1427번 | 소트인사이드 문제 풀이 (Java) (0) | 2025.03.05 |
프로그래머스 42748번 | K번째수 문제 풀이 (Java) (0) | 2025.03.04 |