본문 바로가기
코딩테스트

String 배열 n번째 기준으로 앞뒤 값 바꾸기

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

 

public int[] solution(int[] num_list, int n) {
        int[] answer = new int[num_list.length];        
        int[] front = Arrays.copyOfRange(num_list, 0, n);
        int[] back = Arrays.copyOfRange(num_list, n, num_list.length);
        
        System.arraycopy(back, 0, answer, 0, back.length);
        System.arraycopy(front, 0, answer, back.length, front.length);
        
        return answer;
    }

 

앞 문제에서 말한, Arrays.copyOfRange 그리고 System.arraycopy 가지고 풀어보았다.

 

Arrays.copyOfRange 는 배열의 일정 범위새로운 배열로 복사해서 리턴하고

int[] newArr = Arrays.copyOfRange(원본배열, 시작인덱스, 끝인덱스);

 

System.arraycopy는 원본 배열의 일부를 대상 배열에 복사할 때 쓰인다.

System.arraycopy(원본배열, 원본시작, 대상배열, 대상시작, 복사길이);