10989번: 수 정렬하기 3
첫째 줄에 수의 개수 N(1 ≤ N ≤ 10,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 숫자가 주어진다. 이 수는 10,000보다 작거나 같은 자연수이다.
www.acmicpc.net
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 max = 0;
int[] input = new int[N];
for(int i=0; i<N; i++){
input[i] = Integer.parseInt(br.readLine());
max = Math.max(max, input[i]);
}
int[] counting = new int[max+1];
int[] ans = new int[N];
for(int i=0; i<N; i++){
counting[input[i]]++; //카운팅 배열
}
for(int i=1; i<counting.length; i++){
counting[i] += counting[i-1]; //누적
}
for(int i= input.length-1; i>=0; i--){
ans[--counting[input[i]]] = input[i];
}
for(int i=0; i<N; i++){
bw.write(Integer.toString(ans[i])+'\n');
}
br.close(); bw.close();
}
}
1. Scanner, Print는 모두 시간초과가 난다!
BufferedReader, BufferedWriter를 이용했다.
2. 카운팅 정렬 이용해서 정렬 - 카운팅 정렬 관련 글 참고!
카운팅 정렬 (Counting Sort)
Counting Sort - 원소 간 비교 과정을 거치지 않고 정렬하는 방법 - 시간복잡도 = O(n) - O(nlogn)의 Quick Sort(퀵 정렬)보다 빠르지만, 사용할 수 있는 경우가 제한적이다. : 모든 원소가 양수여야 한다. (배
yeone2ee.tistory.com
'1d-1c > BOJ' 카테고리의 다른 글
1931_회의실배정 (JAVA) (0) | 2020.11.05 |
---|---|
2108_통계학 (JAVA) (0) | 2020.11.04 |
2751_수 정렬하기2 (JAVA) (0) | 2020.10.29 |
1436_영화감독 슘 (JAVA) (0) | 2020.10.29 |
2750_수 정렬하기1 (JAVA) (0) | 2020.10.28 |