포스트

마지막 두 원소

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

문제

  • 문제 풀이
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
class Solution {
    public int[] solution(int[] num_list) {
        int lastIdx = num_list.length - 1;
        
        // 마지막 원소와 그 전 원소 비교
        if (num_list[lastIdx] > num_list[lastIdx - 1]) {
            // 마지막 원소가 그 전 원소보다 큰 경우
            int diff = num_list[lastIdx] - num_list[lastIdx - 1];
            
            // 새로운 배열을 생성하여 기존 배열 복사
            int[] answer = new int[num_list.length + 1];
            System.arraycopy(num_list, 0, answer, 0, num_list.length);
            
            // 새로운 값을 추가
            answer[num_list.length] = diff;
            return answer;
        } else {
            // 마지막 원소가 그 전 원소보다 크지 않은 경우
            int doubledValue = num_list[lastIdx] * 2;
            
            // 새로운 배열을 생성하여 기존 배열 복사
            int[] answer = new int[num_list.length + 1];
            System.arraycopy(num_list, 0, answer, 0, num_list.length);
            
            // 두 배한 값을 추가
            answer[num_list.length] = doubledValue;
            return answer;
        }
    }
}


  • System.arraycopy() 메서드는 배열의 일부분이나 전체를 다른 배열로 복사하는 데 사용된다.

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