[PGM]K번째 수

PearLineZero
|2024. 9. 12. 20:14
티어 : Lv. 1
정답여부 : 정답

💡문제

● K번째 수

 

💡입출력 예

 

💡문제

  • [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소를 array 적용했을 때 나온 결과를 배열을 출력하면 되는 문제
    • i : 시작
    • j : 끝
    • k : 위치

 

💡알고리즘 설계

  1. 각 commands 길이만큼 빼준다.
  2. a , b , c : 값을 담아준다.
  3. 각 a부터 b 만큼 배열을 담아주고 그 배열의 정렬
  4. 다음 c 위치에 있는 배열을 빼서 answer에 담아준다.

 

💡시간복잡도

  • O(NlogN)

 

💡코드

import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
    	int[] answer = new int [commands.length];
    	int idx = 0;
    	for(int i =0; i <commands.length; i++ ) {
    		int a = commands[i][0] - 1;
    		int b = commands[i][1];
    		int c = commands[i][2] - 1;
    		int[] arrs = new int[b - a];
    		int index = 0;
    		for(int j = a; j < b; j++) {
    			arrs[index++] = array[j];
    			
    		}
    		Arrays.sort(arrs);
    		answer[idx++] = arrs[c];
    	}
        
        return answer;
    }
}

 

💡 틀린 이유

통과

근데 깔끔하게 만든 코드를 발견..!!

 

💡 틀린 부분 수정 or 다른풀이

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

        return answer;
    }
}

 

💡 느낀점

코드가 조금 더럽긴 하지만.. 그래도 혼자 스스로 풀어서 뿌듯 ㅎㅎ

'CodingTest > Programmers' 카테고리의 다른 글

[PGM]전화번호 목록  (0) 2024.09.11
[PGM]같은 숫자는 싫어  (0) 2024.09.11
[PGM]경주로 건설  (0) 2024.09.06
[PGM]배달  (0) 2024.09.04
[PGM]미로 탈출  (7) 2024.09.02