。゚(*´□`)゚。

코딩의 즐거움과 도전, 그리고 일상의 소소한 순간들이 어우러진 블로그

ㅋㅌ

**********************System.arraycopy()

quarrrter 2023. 7. 5. 09:32

정수 리스트 num_list와 정수 n이 주어질 때, num_list를 n 번째 원소 이후의 원소들과 n 번째까지의 원소들로 나눠 n 번째 원소 이후의 원소들을 n 번째까지의 원소들 앞에 붙인 리스트를 return하도록 solution 함수를 완성해주세요.

import java.util.Arrays;

class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[num_list.length];
        
        // n 번째 원소 이후의 원소들을 answer 배열의 앞부분에 복사
        System.arraycopy(num_list, n, answer, 0, num_list.length - n);
        
        // n 번째까지의 원소들을 answer 배열의 뒷부분에 복사
        System.arraycopy(num_list, 0, answer, num_list.length - n, n);
        
        return answer;
    }
}

위 코드에서는 System.arraycopy() 메소드를 사용하여 배열의 일부를 다른 배열로 복사합니다. System.arraycopy() 메소드는 소스 배열에서 지정된 범위의 요소를 대상 배열로 복사하는 기능을 제공합니다.

이를 이용하여 num_list 배열에서 n 번째 원소 이후의 원소들을 answer 배열의 앞부분에 복사하고, n 번째까지의 원소들을 answer 배열의 뒷부분에 복사합니다.

예를 들어, num_list가 [1, 2, 3, 4, 5]이고 n이 2일 경우, 결과로 반환되는 answer 배열은 [3, 4, 5, 1, 2]가 됩니다.

 

 

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;
    }
}

'ㅋㅌ' 카테고리의 다른 글

Math  (0) 2023.07.09
부분 문자열 이어 붙여 문자열 만들기  (0) 2023.07.05
묘경이한테 물어보기  (0) 2023.07.03
문자열 정렬하기  (0) 2023.07.01
공백으로 구분하기 2  (0) 2023.06.30