포스트

순서 바꾸기

https://school.programmers.co.kr/learn/courses/30/lessons/181891

문제

  • 문제 풀이
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
29
30
import java.util.Arrays;

public class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] result = new int[num_list.length];
        
        // n 번째 이후의 원소들을 결과 배열에 추가
        int index = 0;
        for (int i = n; i < num_list.length; i++) {
            result[index++] = num_list[i];
        }
        
        // n 번째까지의 원소들을 결과 배열에 추가
        for (int i = 0; i < n; i++) {
            result[index++] = num_list[i];
        }
        
        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] num_list1 = {2, 1, 6};
        int[] num_list2 = {5, 2, 1, 7, 5};
        int[] result1 = sol.solution(num_list1, 1);
        System.out.println(Arrays.toString(result1)); // 출력: [1, 6, 2]
        int[] result2 = sol.solution(num_list2, 3);
        System.out.println(Arrays.toString(result2)); // 출력: [7, 5, 5, 2, 1]
    }
}
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
29
30
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> solution(int[] num_list, int n) {
        List<Integer> result = new ArrayList<>();
        
        // n 번째 이후의 원소들을 결과 리스트에 추가
        for (int i = n; i < num_list.length; i++) {
            result.add(num_list[i]);
        }
        
        // n 번째까지의 원소들을 결과 리스트에 추가
        for (int i = 0; i < n; i++) {
            result.add(num_list[i]);
        }
        
        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] num_list1 = {2, 1, 6};
        int[] num_list2 = {5, 2, 1, 7, 5};
        List<Integer> result1 = sol.solution(num_list1, 1);
        System.out.println(result1); // 출력: [1, 6, 2]
        List<Integer> result2 = sol.solution(num_list2, 3);
        System.out.println(result2); // 출력: [7, 5, 5, 2, 1]
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] result = new int[num_list.length];
        
        // n 번째 이후의 원소들을 result 배열의 앞부분에 복사
        System.arraycopy(num_list, n, result, 0, num_list.length - n);
        
        // n 번째까지의 원소들을 result 배열의 나머지 부분에 복사
        System.arraycopy(num_list, 0, result, num_list.length - n, n);
        
        return result;
    }
}


  • System.arraycopy는 배열 간의 복사를 수행하는 메서드이다. 이 메서드를 사용하여 소스 배열의 일부 또는 전체를 대상 배열의 특정 위치에 복사할 수 있다.
    • System.arraycopy 메서드의 선언은 다음과 같다.

      1
      
        public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
      
      • src: 복사할 소스 배열
      • srcPos: 소스 배열에서 복사를 시작할 위치
      • dest: 복사된 데이터를 저장할 대상 배열
      • destPos: 대상 배열에 데이터를 저장할 위치
      • length: 복사할 요소의 개수
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.