JAVA/프로그래머스

[프로그래머스] 정렬 - K번째수

배고파요 2024. 9. 6. 15:10
728x90

 

📍 생각포인트

  • 2차원 배열은 commands[0][1] 이런식으로 표현된다는 거.
  • Arrays.copyOfRange(복사할 원본 배열, 복사 시작 인덱스, 복사 종료 인덱스);
  • 더보기

     

     

    int[] intArr = new int[] {1, 2, 3, 4, 5};
    int[] intArrCopy = Arrays.copyOfRange(intArr, 2, 4);
    for(int i : intArrCopy) System.out.println(i);
    
    // 출력
    /*
    3
    4
    */
    /* 사실상 Arrays.copyOfRange 는 이렇게 구성된다고 생각할 수 있다.
    int[] tempCopyArr = new int[4-2];
    int k = 0;
    for(int i=2 ; i < 4; i++){
        tempCopyArr[k] = intArr[i];
    }
    */
    출처: https://romcanrom.tistory.com/48 [See, Think, Wonder:티스토리]

 

 

 


📍 방법 1 :: for 문으로 일단 어떻게든 했다 ㅋㅋㅋ

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        // 방법1 :: for문 사용해서.
        int cmmdLength = commands.length;
        int[] answer = new int[cmmdLength];
        
        //System.out.println(Arrays.deepToString(commands));
        for(int i=0; i<cmmdLength; i++){
            int [] cmmd = commands[i];
            int startIndex = cmmd[0];
            int endIndex = cmmd[1];
            int pickIndex = cmmd[2];
                        
            int [] ans = new int[endIndex-startIndex+1];
            int k = 0;
            for(int j=startIndex-1; j<endIndex; j++){
                ans[k] = array[j];
                k++;
            }
            Arrays.sort(ans);
            
            //System.out.println(Arrays.toString(ans));
            answer[i] = ans[pickIndex-1];
        }
        return answer;        
    }
}

 

 

 

 

📍 방법2 :: Arrays.copyOfRange() 사용

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        
        // 방법2 :: Arrays.copyOfRange() 써서!
        int[] answer = new int[commands.length];
        for(int i=0; i<commands.length; i++){
            int[] cmmd = commands[i];
            int[] intArrCopy = Arrays.copyOfRange(array, cmmd[0]-1, cmmd[1]);
            Arrays.sort(intArrCopy);
            answer[i] = intArrCopy[cmmd[2]-1];
        }
        
        // 2차원 배열로 해보면
        for(int i=0; i<commands.length; i++){
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }     
        return answer;
    }
}

 


출처 : 

https://hianna.tistory.com/511

https://romcanrom.tistory.com/48

 

 


개발 공부를 위한 블로그 입니다. 

오류가 있다면 댓글로 알려주세요! 

감사합니다.

728x90