K번째수
2023. 1. 19. 21:02ㆍProgrammers/Java
문제
예제
코드
1) Arrays.copyOfRange
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = {};
int[] temp = new int[commands.length];
for(int i=0; i <commands.length; i++) {
answer = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
Arrays.sort(answer);
temp[i] = answer[commands[i][2]-1];
}
return temp;
}
}
|
cs |
answer : 지정 크기만큼 자른 원소를 담을 배열
temp : 조건에 맞는 원소가 들어갈 최종 배열
copyOfRange(원본배열, 복사 시작할 인덱스, 복사 끝낼 인덱스)
랜덤으로 배열을 주면 그 배열에서 m부터 n까지 뽑아서 p번째 원소를 출력하는 문제다.
주어진 원소의 개수만큼 복사해서 answer 배열에 넣고
Arrays.sort()로 크기대로 정렬한다.
p번째 원소들을 temp에 담아준다.
p번째 원소는 인덱스가 p인게 아니라 p-1이므로 13번째 줄에서 -1을 해주었다.
'Programmers > Java' 카테고리의 다른 글
두 개 뽑아서 더하기 (0) | 2023.01.29 |
---|---|
문자열 내 p와 y의 개수 (0) | 2023.01.21 |
자릿수 더하기 (0) | 2023.01.19 |
숫자 문자열과 영단어 (0) | 2023.01.18 |
짝수와 홀수 (0) | 2023.01.17 |