코딩테스트/프로그래머스
[JAVA] - K번째수
애플쩀
2022. 6. 21. 06:24
import java.util.ArrayList;
import java.util.Collections;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
ArrayList<Integer> arr=new ArrayList<>();
for (int i = 0; i < commands.length; i++) {
int start=commands[i][0]-1;
int end=commands[i][1];
int pick=commands[i][2]-1;
for (int j = start; j <end; j++) {
arr.add(array[j]);
}
Collections.sort(arr);
answer[i]=arr.get(pick);
arr.clear();
}//for
return answer;
}
}
- 답을 반환할 배열을 만들어 주고 ,
- 새로 추출한 배열을 생성해준다.
- commands 2차원배열의 (세로) 크기만큼 for문을 돌려주고
- start에는 첫번째수, end에는 두번째 수, pick에는 3번째 수를 담아주는데
- 인덱스로 이용되기때문에 -1씩빼준다.
- end는 부등호때문에 알아서 걸러지니 -1을 안해도 된다.
- 지정된 인덱스로 다시 for문을 돌려서 arrayList에 추가를 해준다
- sort()함수로 정렬을 해주고
- answer에 arr 배열의 pick 번째인덱스를 돌려준다.
내 코드에서 느낀점
- int start, end, pick 처럼 변수를 선언하지 않고 바로 썼다면 더 깔끔했었을것같고
- 처음에 실패가 떠서 이유를 생각해보니 배열을 비워주지 않고 계속 누적시켜줬었다.
- claer()함수로 배열을 비워준다.
- ArrayList를 for문 안에 선언하면 다음배열순으로 넘어갈때마다 알아서 초기화되어서 clear를 쓸 필요가 없다.
개선한 코드
import java.util.ArrayList;
import java.util.Collections;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
ArrayList<Integer> arr=new ArrayList<>();
for (int j = commands[i][0]-1; j <commands[i][1]; j++) {
arr.add(array[j]);
}
Collections.sort(arr);
answer[i]=arr.get(commands[i][2]-1);
}//for
return answer;
}
}
다른사람 풀이
Arrays.copyOfRange() 사용하기
Arrays.copyOfRange(a,b,c);
// 원본 배열, 복사할 시작인덱스, 복사할 끝인덱스+1
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];
}//for
return answer;
}
}
- Arrays.copyOfRange로 배열을 복사한뒤 바로 정렬하고 해당인덱스의 값을 가져온다.