📊 Algorithm&SQL
[Java/프로그래머스] K번째 수
오늘 ONEUL
2022. 12. 11. 16:52
문제
풀이
(1) 문제 분석하기
- 정답 배열의 길이를 입력받은 commands의 길이로 설정
- 입력값이 2차원 배열로 주어지므로 반복문을 돌면서 연산
- 배열을 특정 인덱스로 자르기 위해 Arrays.copyOfRange 사용하여 원본 배열 복사
- Array.copyOfRange(array, startIndex, lastIndex)
int[] array = {1, 2, 3, 4, 5};
int[] result = Arrays.copyOfRange(array, 1, 4);
// result : [2, 3, 4]
// 마지막 인덱스 포함X
(2) 슈도코드 작성하기
int형 정답 배열의 길이를 commands의 길이로 설정
for(commands의 길이만큼) {
commands의 0, 1, 2번째 수를 변수에 담음
배열을 특정 인덱스로 잘라서 복사
복사한 배열 오름차순으로 정렬
복사한 배열의 (commands[i][2])번째 수를 정답 배열에 추가
}
정답 배열 리턴
(3) 코드 구현하기
package algorithm.test29;
import java.util.Arrays;
public class Solution {
// int형 정답 배열의 길이를 commands의 길이만큼 설정
// commands for문을 돌면서
// copyOfRange 메서드를 이용하여 배열을 자르고
// 배열을 정렬
// k번째 수를 정답 배열에 넣기
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
int a = commands[i][0];
int b = commands[i][1];
int c = commands[i][2];
int[] result = Arrays.copyOfRange(array, a - 1, b);
Arrays.sort(result);
answer[i] = result[c - 1];
}
return answer;
}
public static void main(String[] args) {
int[] array = {1, 5, 2, 6, 3, 7, 4};
int[][] commands = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};
Solution sol = new Solution();
for (int i : sol.solution(array, commands)) {
System.out.println(i);
}
}
}
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr