- 내 풀이
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = {};
answer = new int[3];
for (int i = 0; i < commands.length; i++) {
int start = commands[i][0]-1;
int end = commands[i][1];
int middle = commands[i][2];
int[] check = new int[end-start];
for (int j = 0; j < check.length; j++) {
check[j] = array[j+start];
}
Arrays.sort(check);
answer[i] = check[middle-1];
}
return answer;
}
}
실행은 성공 --> 제출 후 채점하기는 실패
뭐가 문제인지 하나씩 바꿔보다가 answer = new int[3] 이 문제라는 걸 알게 되었음
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = {};
// commands의 개수 만큼 숫자가 나옴
answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
// 굳이 변수에 담지 않아도 되는데 일일이 쓰기 귀찮아서 담아둠
// [0][0] 에서 [0][1] 까지의 숫자를 가져와야하는데 -1을 하지 않으면 본인을 포함하지 않게 된다
int start = commands[i][0]-1;
int end = commands[i][1];
int middle = commands[i][2];
int[] check = new int[end-start];
for (int j = 0; j < check.length; j++) {
check[j] = array[j+start];
}
//정렬한 숫자에서 [0][2] 번째의 숫자를 불러와야함
Arrays.sort(check);
// 배열에 있기 때문에 -1해줘야함
answer[i] = check[middle-1];
}
return answer;
}
}
- 다른 사람 풀이
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를 저렇게 쓰는거구나
'프로그래머스 > [프로그래머스 - JAVA] Lv.1' 카테고리의 다른 글
[프로그래머스 - JAVA] 두 개 뽑아서 더하기 (0) | 2023.04.04 |
---|---|
[프로그래머스 - JAVA] 크기가 작은 부분문자열 (0) | 2023.04.04 |
[프로그래머스 - JAVA] 숫자 문자열과 영단어 (0) | 2023.04.03 |
[프로그래머스 - JAVA] 문자열 내 마음대로 정렬하기 (0) | 2023.04.03 |
[프로그래머스 - JAVA] [1차] 비밀지도 - 17년도 카카오 1차 코딩테스트 (0) | 2023.04.03 |
댓글