코테 문제풀이
[백준] 2750번 : 수 정렬하기 - JAVA [자바]
ddubi__
2022. 12. 18. 19:04
https://www.acmicpc.net/problem/2750
2750번: 수 정렬하기
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수가 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
www.acmicpc.net
• 런타임 에러 (ArrayIndexOutOfBounds)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main { // 정렬하기
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
int[] count = new int[1001];
int[] result = new int[N];
for(int i=0; i<arr.length; i++){
arr[i] = Integer.parseInt(br.readLine());
count[arr[i]] ++;
}
for(int i=1; i<count.length; i++){
count[i] += count[i-1];
}
for(int i=arr.length-1; i>=0; i--){
int value = arr[i];
count[value] --;
result[count[value]] = value;
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
}
}
• 풀이 (정렬 하지않고 counting sort 이용)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main { // 정렬하기
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
// -1000 ~ 1000의 범위 -> 0~2000 인덱스에 넣어줌(+1000된 값)
boolean[] arr = new boolean[2001];
for(int i=0; i<N; i++){
arr[Integer.parseInt(br.readLine()) +1000] = true;
}
// 값 중복이 없기 때문에 정렬기능이 필요없다. 그냥 true인것 프린트하면 됨
for (int i=0; i<arr.length; i++){
if(arr[i]) System.out.println(i-1000);
}
}
}