문제
K번째수
https://programmers.co.kr/learn/courses/30/lessons/42748?language=java
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한 사항
- array의 길이는 1 이상 100 이하입니다.
- array의 각 원소는 1 이상 100 이하입니다.
- commands의 길이는 1 이상 50 이하입니다.
- commands의 각 원소는 길이가 3입니다.
생각해보기
- 정렬 메소드를 정의하는 방법
- Collections.sort()를 사용하는 방법
- 현재 문제에서 나오는 command i와 j번째는 array에서는 인덱스가 0으로 시작하기 때문에 i-1과 j-1번째로 파악!
Code
- answer값은 commands의 길이로 초기화한다.
- commands 안에 각각의 command에서 하나의 값씩 나오기 떄문
- 먼저 for문을 통해 commands에서 command를 추려 i, j, k를 선언과 초기화를 한다.
- array에서 i-1번째부터 j-1번째까지 값을 list(or arr)에 넣어둔다.
- 배열은 인덱스가 0부터 시작하기 때문에 i와 j가 아닌 i-1과 j-1로 표현
- list(or arr)를 오름차순으로 정렬한다.
- list(or arr)에서 k-1번째 값을 찾아 answer 배열에 넣어 commands배열에 끝날 때까지 반복한다.
- 첫번째 command
- 두번째 command
- 세번째 command
Java
- ArrayList와 Collections.sort 풀이
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length]; // 정답을 넣은 배열
int cnt = 0; // 배열에 들어갈 인덱스 번호
for(int[] command: commands) {
int i = command[0];
int j = command[1];
int k = command[2];
// i ~ j번째 값을 넣은 리스트
List<Integer> list = new ArrayList<>();
for (int l = i - 1; l < j; l++) {
list.add(array[l]);
}
Collections.sort(list); // 정렬
// 원하는 k번째 값을 결과 배열에에 넣어줌
answer[cnt++] = list.get(k - 1);
}
return answer;
}
}
- int배열과 sort메서드 정의한 풀이
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length]; // 정답을 넣은 배열
int cnt = 0; // 배열에 들어갈 인덱스 번호
for(int[] command: commands) {
int i = command[0];
int j = command[1];
int k = command[2];
// i ~ j번째 값을 넣은 배열
int[] arr = new int[j - i + 1];
int tmp = 0;
for (int l = i - 1; l < j; l++) {
arr[tmp++] = array[l];
}
sort(arr); // 정렬
// 원하는 k번째 값을 결과 배열에 넣어줌
answer[cnt++] = arr[k - 1];
}
return answer;
}
// 정렬 메소드
public static void sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
for (int j = i; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
int tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
} else {
break;
}
}
}
}
}
테스트 결과
- ArrayList에 담고 정렬은 Collections.sort()로 했을 경우
- int배열에 담고 sort메서드 정의한 후 정렬했을 경우
반응형
'Algorithm > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 모의고사 (0) | 2023.01.10 |
---|---|
[프로그래머스] 더 맵게 (0) | 2022.12.29 |
[프로그래머스] 기능개발 (0) | 2022.12.28 |
[프로그래머스] 완주하지 못한 선수 (0) | 2022.10.27 |