본문 바로가기
카테고리 없음

[BOJ_JAVA] 백준 10989번 : 수 정렬하기3 @달깅

by 달깅 2019. 11. 10.

https://www.acmicpc.net/problem/10989

 

이거는 설명에 보니까 카운팅 정렬로 풀으라고 적혀있었다.

여기서 카운팅 정렬이라는 말을 처음 들어봐서 구글링 해서 찾아봤다 ㅎㅎ

처음에는 그 더하는 부분? 그니까 count array를 다시 앞의 원소랑 더하는 부분까지 구현해서 했는데 

그렇게 하니까 시간 초과가 나왔다. 아마 bufferedwriter을 안써서 그런 것 같은데,

그걸 쓰니까 금방 해결이 됐다

맨날 스캐너만 쓰다가 이제 좀 익숙해지려고

bufferedreader만 쓰려고 노력중인데

오늘 처음으로 bufferedwriter도 써봤다. 앞으로도 이것만 써서 좀 더 익숙해져야겠다!

 


정답코드

 

 

import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            int n=Integer.parseInt(br.readLine());
            int max=0;
            int[] arr=new int[n];

            for (int i=0; i<n; i++) {
                arr[i]=Integer.parseInt(br.readLine());
                if (arr[i]>max) {
                    max=arr[i];
                }
            }

            int[] count=new int[max];

            for (int i=0; i<n; i++) {
                count[arr[i]-1]++;
            }

            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));

            for (int i=0; i<max; i++) {
                if (count[i]!=0) {
                    while(count[i]>0) {
                        bw.write(Integer.toString(i+1)+"\n");
                        count[i]--;
                    }
                    
                }
            }
            bw.close();
        
        } catch (IOException e) {}
    }
}

댓글