문제
코드
시도 1 - O
commands[][]
의 행을 돌며 i ~ j 인덱스의 값들을 새로운 배열에 복사한 뒤 k번째 값을 result[]
배열에 삽입하여 반환한다.
/** 문제 설명
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수 구하기
*/
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] result = new int[commands.length];
int s = 0;
for (int[] command : commands) {
int i = command[0];
int j = command[1];
int k = command[2];
ArrayList<Integer> al = new ArrayList<>();
for (int index = i-1; index < j; index++) {
al.add(array[index]);
}
al.sort(null); // 2 3 5 6
result[s++] = al.get(k-1); // 5
}
return result;
}
}
시도 1 코드 개선 - O
Arrays 클래스에 copyOfRange()
메서드를 사용한 코드이다.
코드 가독성은 더 좋아졌지만 시간이 더 오래 걸리는 단점이 있다.
Arrays.copyOfRange(원본 배열, 시작 인덱스,끝 인덱스)
원본 배열의 시작 인덱스 ~ 끝 인덱스의 값을 새로운 배열에 복사하여 새로운 배열을 반환해주는 메소드이다.
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] result = new int[commands.length];
int s = 0;
for (int[] command : commands) {
int i = command[0];
int j = command[1];
int k = command[2];
ArrayList<Integer> al = new ArrayList<>();
int[] temp = Arrays.copyOfRange(array, i-1, j);
Arrays.sort(temp);
result[s++] = temp[k-1];
}
return result;
}
}
'코딩 테스트 > 자료구조' 카테고리의 다른 글
[프로그래머스] 42746 가장 큰 수(Lv.2) - 정렬 (0) | 2024.07.05 |
---|---|
[백준] 9372 상근이의 여행(실버4) - 그래프 (0) | 2024.07.05 |
[프로그래머스] 49189 가장 먼 노드(Level3) - 그래프, BFS (0) | 2024.07.05 |
[백준] 2178 미로 탐색(실버1) - 그래프 (0) | 2024.07.04 |
[백준] 2606 바이러스(실버3) - 그래프(DFS) (0) | 2024.07.03 |