Dev/Programmers

[프로그래머스] K번째수 (Java)

마이캣호두 2024. 12. 16. 15:08
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/42748

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

Review

tmi) 오늘의 목표는 프로그래머스 알고리즘 고득점 Kit 의 정렬 파트 모두 풀기다!

 

아래 코드는 과거에 풀었던 코드를 가져온 것.

과거에 풀었던 방식이 시각적으로는 조금 더 깔끔해 보이지만, 다른 사람의 코드라고 가정했을 때는 변수를 선언해서 의미를 명확히 하는 것이 더 좋은 방식이라고 생각하기에 오늘은 이렇게 풀었다!

 

 

Code

import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        for (int i = 0; i < commands.length; i++) {
            int s = commands[i][0] - 1;
            int e = commands[i][1];
            int k = commands[i][2] - 1;
            
            int[] tmp = Arrays.copyOfRange(array, s, e);
            Arrays.sort(tmp);
            
            answer[i] = tmp[k];
        }
        return answer;
    }
}

 

 

import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        for (int i = 0; i < commands.length; i++) {
            int[] arr = {};
            for (int j = 0; j < commands[i].length; j++) {
                arr = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
                Arrays.sort(arr);
            }
            answer[i] = (arr[commands[i][2] -1]);
        }
        
        return answer;
    }
}
반응형