본문 바로가기

Coding Test/Programmers

[JAVA] 정렬 Lv.1 / K번째 수

[문제]

[제한 사항]

  • array의 길이는 1 이상 100 이하입니다.
  • array의 각 원소는 1 이상 100 이하입니다.
  • commands의 길이는 1 이상 50 이하입니다.
  • commands의 각 원소는 길이가 3입니다.

[알고리즘]

배열 array와 이차원 배열 commands 가 주어지고 commands 안에 i,j,k 가 주어지는 문제이다.

문제 상 i 는 commands[][0]에 해당하고, j는 commands[][1]에 해당
이중 for 문을 사용하여 문제를 해결해주기로 했다.

첫 for문의 범위는 0부터 commands의 길이까지이고, 두번째 for문은 commands[i][0]부터 commands[i][1]까지로 작성해준다.


여기서 commands[i][0]-1의 이유는 array[j]시 인덱스를 맞게 찾아가게 하기 위해서이다.

array commands
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]]


ex)commands[0][0] = 2   = >  array[2] 값은 우리가 원하는 array의 2번째 인덱스 값인 "5"가 아닌 "2"가됨 
     ∴  -1을 해야 값이 찾으려는 값이 나옴

인덱스번호 [0] [1] [2] [3] [4] [5] [6]
1 5 2 6 3 7 4

tmpArr 변수에 찾으려는 값의 범위를 저장해주고 두번째 for문 바깥에서 Arrays.sort()사용하여 정렬한뒤 두번째  k번째 숫자를 찾으려면 answer[i] = tmpArr[commands[i][2]-1]을 해주면된다.

[코드]

import java.util.*;
class Solution{
public int[] solution(int[] array,int[][] commands) {
    int[] answer = new int[commands.length] ;
    for(int i=0;i<commands.length;i++){
        int[] tmpArr = new int[commands[i][1]-commands[i][0]+1];    //배열의 크기 맞추기 위해 +1
    int idx =0;     //커맨드  순서를 위한 변수
        for(int j= commands[i][0]-1; j< commands[i][1]; j++){   //commands[i][0]-1 : index에 맞게 찾아가게 하기 위해서
            tmpArr[idx]=array[j];
            idx++;  //다음 커맨드
        }
        Arrays.sort(tmpArr);        //정렬 (오름차순)
        answer[i] = tmpArr[commands[i][2]-1];
    }
    return answer;
  }
}