Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags more
Archives
Today
Total
관리 메뉴

David의 블로그

프로그래머스 - 순서바꾸기 본문

프로그래밍/코딩

프로그래머스 - 순서바꾸기

David 리 2024. 5. 25. 11:05

문제설명 >

정수 리스트 num_list와 정수 n이 주어질 때, 

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

 

예시결과 >

num_list           n        result
[2, 1, 6]            1        [1, 6, 2]
[5, 2, 1, 7, 5]    3        [7, 5, 5, 2, 1]

 

 

나의 생각.

n인덱스 이후의 값들을 앞에 붙이고, 나머지 원소값들을 붙이면 되겠다. 생각하여 

for문 2번과 List<Integer>를 이용하여 구현해냈다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        int[] num_list = {216};
        int n = 1;
        int[] answer = new int[num_list.length];
        
        List<Integer> intList = new ArrayList<Integer>();
        
        for (int i = 0; i < num_list.length; i++) {
            if (i >= n) 
            {
                intList.add(num_list[i]);
            }
        }
        
        if (num_list.length != intList.size())
        {
            int diff = num_list.length - intList.size();
            for (int i = 0; i < diff; i++) {
                intList.add(num_list[i]);
                
            }
        }
        answer = intList.stream().mapToInt(i -> i).toArray();
        System.out.println(Arrays.toString(answer));
cs

 

 

 

나의 풀이도 맞았지만, 다른 사람의 풀이도 한번 확인해봤다.

1
2
3
4
5
6
7
8
        int[] num_list = {216};
        int n = 1;
        int[] answer = new int[num_list.length];
        
        for (int i = 0; i < num_list.length; i++) {
            answer[i] = num_list[(i + n) % num_list.length];
        }
        System.out.println(Arrays.toString(answer));
cs

더 간단했다. 

간단히 산술식을 이용해 이용할 수 있다.