문제
내가 작성한 정답
Array이용
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = new int[num_list.length];
for(int i=0; i<num_list.length-n; i++){
answer[i] = num_list[n+i];
}
for(int i=0; i<n; i++){
answer[num_list.length-n+i] = num_list[i];
}
return answer;
}
}
StreamAPI이용
import java.util.stream.IntStream;
class Solution {
public int[] solution(int[] num_list, int n) {
return IntStream.concat(
IntStream.range(n,num_list.length).map(i->num_list[i]),
IntStream.range(0,n).map(i->num_list[i])
).toArray();
}
}
다른 사람들의 정답
import java.util.stream.IntStream;
class Solution {
public int[] solution(int[] num_list, int n) {
return IntStream.range(0, num_list.length)
// 각 인덱스 i에 대해 (i + n) % num_list.length를 계산하여 num_list에서 해당 인덱스의 값을 가져온다.
// -> 배열을 n만큼 회전시키는 효과
.map(i -> num_list[(i + n) % num_list.length])
.toArray();
}
}
class Solution {
public int[] solution(int[] num_list, int n) {
int idx = 0;
int[] answer = new int[num_list.length];
for (int i = n;i < num_list.length;i++)
answer[idx++] = num_list[i];
for (int i = 0;i < n;i++)
answer[idx++] = num_list[i];
return answer;
}
}
Share article