차곡차곡 성 쌓기
article thumbnail

문제

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

 

1427번: 소트인사이드

첫째 줄에 정렬하려고 하는 수 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수이다.

www.acmicpc.net

 

접근법

N은 최대 10자리 숫자로 매우 큰 메모리 공간을 차지함. 하지만 이 문제는 자릿수의 숫자들을 뽑아 정렬하는 것이므로 String 객체로 입력을 받아 쪼개 Int형 배열로 만드는 것이 효율적이라 생각이 들었다. 그 후 최대 10개의 숫자를 정렬하는 것은 아무 정렬법이나 쓰면 된다.

 

풀이 코드

public class Main {
    public static void main(String[] args) throws IOException {
        // 문자열로 입력 받기
        Scanner sc = new Scanner(System.in);
        String sNum = sc.next();

        // 숫자 배열로 만들기
        char [] cNum = sNum.toCharArray();
        int N = cNum.length;
        int [] nums = new int[N];

        for(int i=0; i< N; i++){
            nums[i] = Character.getNumericValue(cNum[i]);
        }

        // 정렬 (선택 정렬)
        for(int i=0; i < N-1; i++){
            int max = i;
            for(int j= i+1; j< N; j++){
                if(nums[max] < nums[j])
                    max = j;
            }
            if(max != i)
                swap(i, max, nums);
        }

        // 출력
        for(int i=0; i< N; i++){
            System.out.print(nums[i]);
        }

    }

    public static void swap(int first, int second, int [] array){
        int temp = array[first];
        array[first] = array[second];
        array[second] = temp;
    }
}
728x90
profile

차곡차곡 성 쌓기

@nagrang

포스팅이 좋았다면 "좋아요" 해주세요!