프로그래머스 순서 바꾸기

KIMYEONGJUN·2026년 6월 17일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

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

내가 이 문제를 보고 생각해본 부분

main 메서드에서는 Main54 클래스의 인스턴스를 생성하고, solution 메서드를 호출하여 각각 (2, 1, 6)과 n=1, (5, 2, 1, 7, 5)와 n=3에 대해 결과를 받아 출력한다.
solution 메서드의 역할은 주어진 num_list에서 n번째 이후 인덱스의 원소들을 먼저 배열에 복사하고, 그 다음으로 n번째까지의 원소들을 복사해 새로운 배열을 반환하는 것이다.
내부에서 사용하는 idx 변수는 새 배열 answer에 요소를 추가할 위치를 추적한다.
첫 번째 반복문은 num_list의 인덱스 n부터 끝까지 돌면서 값을 answer의 앞 부분부터 넣는 작업을 한다.
두 번째 반복문은 num_list의 인덱스 0부터 n-1까지의 원소를 뒤에 이어 붙인다.
모든 작업이 끝나면 재배치된 answer 배열을 반환한다.

코드로 구현

class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[num_list.length];
        int idx = 0;

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

프로그래머스 코드

package programmers;

import java.util.Arrays;

// 프로그래머스 순서 바꾸기
public class Main54 {
    public static void main(String[] args) {
        Main54 s = new Main54();

        int[] num_list1 = {2, 1, 6};
        int n1 = 1;
        int[] result1 = s.solution(num_list1, n1);
        System.out.println(Arrays.toString(result1));

        int[] num_list2 = {5, 2, 1, 7, 5};
        int n2 = 3;
        int[] result2 = s.solution(num_list2, n2);
        System.out.println(Arrays.toString(result2));
    }

    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[num_list.length];
        int idx = 0;

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

위에 있는 코드를 변경한 코드

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글