문제 링크 : https://www.acmicpc.net/problem/1015
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
// 배열의 크기
int N = Integer.parseInt(br.readLine());
// 원본 배열
int[][] A = new int[N][2];
// 정렬 배열
int[] B = new int[N];
String[] temp = br.readLine().split(" ");
for (int i = 0; i < N; i++)
{
A[i][0] = Integer.parseInt(temp[i]);
A[i][1] = i;
}
// 정렬 수행
sort(A);
for (int i = 0; i < N; i++)
{
int index = A[i][1];
B[index] = i;
}
for (int b : B)
{
sb.append(b).append(" ");
}
System.out.println(sb.toString().trim());
bw.close();
br.close();
}
private static void sort(int[][] A)
{
Arrays.sort(A, (next, current) ->
{
//현재값이 더 클 경우
if (next[0] < current[0]) return -1;
// 다음값이 더 클 경우
else if (next[0] > current[0]) return 1;
// 현재값과 다음값이 같을 경우, 사전순 정렬
else return Integer.compare(next[1], current[1]);
});
}
}
사실상 해당 문제 같은경우 정렬의 기본적인 문제라고 볼 수 있으며,
코드에 주석처리가 되어있어, 이해하기 쉬울 것입니다.
그래도 필자는 간단하게나마 코드에 대해 설명해드리겠습니다.
해당 코드의 전체적인 로직은 주어진 배열을 특정 기준(값과 인덱스)에 따라 정렬하는 알고리즘을 구현한 것이라고 보시면 됩니다.
즉, 값을 기준으로 오름차순 정렬하고, 동일한 값이 있을 경우 인덱스 순서대로 정렬합니다.