[프로그래머스/Java] Lv.0 순서 바꾸기

febCho·2024년 3월 10일
0

코딩테스트

목록 보기
62/253
post-thumbnail

문제

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

- 제한사항

  • 2 ≤ num_list의 길이 ≤ 30
  • 1 ≤ num_list의 원소 ≤ 9
  • 1 ≤ n ≤ num_list의 길이

풀이

Arrays.copyOfRange()를 통해 조건에 맞게 각각 배열을 복사한 다음, for문을 통해 두 배열을 합쳤다. 이때 관건은 두 개의 for문에서 함께 공유하며 사용할 index 값을 정의하는 것!

import java.util.Arrays;

class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] afterN = Arrays.copyOfRange(num_list, n, num_list.length);
        int[] untilN = Arrays.copyOfRange(num_list, 0, n);

        int[] answer = new int[afterN.length + untilN.length];
        int index = 0;
        
        for (int i = 0; i < afterN.length; i++) {
            answer[index++] = afterN[i];
        }
        for (int i = 0; i < untilN.length; i++) {
            answer[index++] = untilN[i];
        }
        
        return answer;
    }
}

결과

profile
Done is better than perfect.

0개의 댓글