K번째 수 (자바) v2

김재현·2024년 4월 25일
0

알고리즘 풀이

목록 보기
79/89
post-thumbnail

이전의 풀이: K번째 수 첫, 풀이

문제

정답 풀이

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++) {
            List<Integer> comArr = new ArrayList<Integer>();
            for(int j=0;j<commands[i][1]-commands[i][0]+1;j++) {
                comArr.add(array[commands[i][0]+j-1]);
            }
            Collections.sort(comArr);
            answer[i] = comArr.get(commands[i][2]-1);
        }
        
        return answer;
    }
}

이번에 풀 때는 ListCollections.sort()를 이용해서 풀어냈다.

List형 자료구조: Collections.sort()
배열: Arrays.sort()

다른 풀이

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[] tmp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(tmp);
            answer[i] = tmp[commands[i][2]-1];
        }
        
        return answer;
    }
}

이전 포스팅을 보고 Arrays.copyOfRange()가 있다는 것을 보고 다시 풀어봤다.
기억을 위해 정리해놓기!

Arrays.copyOfRange(int[] original, int from, int to)

  • original: 복사할 배열
  • from: 복사를 시작할 인덱스(포함).
  • to: 복사를 끝낼 인덱스(제외).
profile
I live in Seoul, Korea, Handsome

0개의 댓글