[백준] 1015번 수열 정렬 - Java, 자바

Kim Ji Eun·2022년 3월 24일
0

난이도

실버 4

문제

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

풀이

  1. Pair 클래스 생성
  2. 리스트에 입력값을 넣기
  3. 리스트 오름차순 정렬하기
  4. 오름차순 정렬된 리스트에 값 차례대로 넣기

문제이해가 잘 되지 않아 나름대로 이해하여 풀어봤다.

코드

package 정렬;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class BOJ1015 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        StringTokenizer st = new StringTokenizer(br.readLine());

        ArrayList<Pair> list = new ArrayList<>();
        for(int i=0;i<n;i++){
            list.add(new Pair(i,Integer.parseInt(st.nextToken())));
        }

        Collections.sort(list, new Comparator<Pair>(){
           @Override
           public int compare(Pair o1, Pair o2){
               if(o1.value<o2.value){ // value 기준 오름차순
                   return -1;
               }else if(o1.value>o2.value){
                   return 1;
               }else{
                   if(o1.idx <o2.idx){
                       return -1;
                   }else{
                       return 1;
                   }
               }
           }
        });

        int[] p = new int[1001];
        for(int i=0;i<n;i++){
            p[list.get(i).idx]=i;
        }

        for(int i=0;i<n;i++){
            System.out.print(p[i]+" ");
        }

    }

    public static class Pair{
        int idx;
        int value;

        Pair(int idx,int value){
            this.idx = idx;
            this.value = value;
        }
    }
}

https://mygumi.tistory.com/118

profile
Back-End Developer

0개의 댓글