프로그래머스 - k번째 수 (Level 1)
2024. 1. 20. 03:07ㆍ코딩테스트 정리(자바)
728x90
나의 풀이
import java.util.*;
class Solution {
public int Ksort(int i, int j, int k, int[] array){
int index=0;
int[] arr=new int[j-i+1];
int num=0;
for(index=i-1;index<j;index++){
arr[num++]=array[index]; //옮겨담기
}
Arrays.sort(arr);
return arr[k-1];
}
public int[] solution(int[] array, int[][] commands) {
int[] answer=new int[commands.length];
for(int index=0;index<commands.length;index++){
int[] command=commands[index];
int i=command[0];
int j=command[1];
int k=command[2];
answer[index]=Ksort(i,j,k,array);
}
return answer;
}
}
더 좋은 코드
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer=new int[commands.length];
for(int index=0;index<commands.length;index++){
int[] command=commands[index];
int i=command[0]-1;
int j=command[1];
int k=command[2]-1;
int[] copy=Arrays.copyOfRange(array,i,j);
Arrays.sort(copy);
answer[index]=copy[k];
}
return answer;
}
}
1.
배열을 복사하는 메서드가 존재한다.
바로 Arrays.copyOfRange( array, from, to)
: array는 원본 배열
from은 복사할 시작 인덱스
to는 복사할 끝 인덱스 (포함 안됨)
값에 의한 복사이므로 복사된 배열의 값을 바꿔도 원본의 값은 바뀌지 않는다.
int[] copy=Arrays.copyOfRange(array,i,j);728x90
'코딩테스트 정리(자바)' 카테고리의 다른 글
| 프로그래머스 - H-Index (Level 2) (2) | 2024.01.22 |
|---|---|
| 프로그래머스 - 두개 뽑아서 더하기( Level 1) (1) | 2024.01.20 |
| 프로그래머스 - 불량 사용자(Level 3) (0) | 2024.01.18 |
| 프로그래머스 - 소수 찾기(Level 2) (0) | 2024.01.16 |
| 프로그래머스 - 수식 최대화(Level 2) (0) | 2024.01.15 |