728x90
문제
https://programmers.co.kr/learn/courses/30/lessons/42748
코딩테스트 연습 - K번째수
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
해결
Arrays.copyOfRange(원본 배열, 원본 배열에서 복사할 시작 인덱스, 마지막으로 복사될 배열 요소의 바로 다음 인덱스)
1
2
3
4
5
6
7
8
9
10
11
|
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOfRange(arr1, 2, 4);
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
// 실행 결과 : 3 4
|
cs |
Arrays.sort()
sort() 메소드는 전달받은 배열의 모든 요소를 오름차순으로 정렬한다.
1
2
3
4
5
6
7
8
9
10
|
int[] arr = {5, 3, 4, 1, 2};
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
// 실행 결과 : 1 2 3 4 5
|
cs |
https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Arrays.html
Arrays (Java SE 16 & JDK 16)
public class Arrays extends Object This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The methods in this class all throw a NullPo
docs.oracle.com
구현
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import java.util.*;
public class Solution {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int[] array = { 1, 5, 2, 6, 3, 7, 4 };
int[][] commands = { { 2, 5, 3 }, { 4, 4, 1 }, { 1, 7, 3 } };
System.out.println(Arrays.toString(solution(array, commands)));
}
public static 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;
}
}
|
cs |
728x90
댓글