코테/프로그래머스

[프로그래머스/Lv. 1] K번째수 (JAVA)

imname1am 2023. 10. 15. 23:52
반응형

🔺 문제

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

🔺 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
 
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        
        int outIdx = 0;
        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];    // array의 i~j번째 숫자까지 저장할 배열
            int idx = 0;
            
            for(int j = commands[i][0- 1 ; j < commands[i][1] ; j++) {    // 1. array의 i~j번째 숫자까지 자르기
                tmpArr[idx++= array[j];
            }
            Arrays.sort(tmpArr);    // 2. 정렬하기
            answer[outIdx++= tmpArr[commands[i][2- 1];    // 3. k번째 있는 수 구하고 정답 배열에 저장하기
        }
        
        return answer;
    }
}
cs

 

 

🧩 해결 아이디어

• array의 i부터 j번째 숫자까지 자르며 임시 배열 tmpArr에 값을 저장하고, 이를 오름차순으로 정렬한다.

• 이 배열에서 k번째에 있는 수를 구하고 정답 배열에 값을 집어넣는다.

 

 


🔺 다른 풀이들

- i~j번째 숫자까지를 저장한 배열을 만들기 위해 Arrays.copyOfRange()를 사용하셨다.... 우와웅....

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

        return answer;
    }
}

 


💬 느낀 점

나도 다음엔 Arrays.copyOfRange()를 사용해볼테야...

 

 

1회독 2회독 3회독 4회독 5회독
V        
반응형