코딩테스트/프로그래머스

[프로그래머스] Lv.0 마지막 두 원소(Java) ※

선SEON 2023. 11. 1. 23:58

1. 문제

2. 제출 답안

public int[] solution(int[] num_list) {
    int size = num_list.length; // 원본 배열의 크기 저장

    int last = num_list[size - 1];  // 마지막 원소
    int prev = num_list[size - 2];  // 그 전 원소
	
    int additionalValue = (last > prev) ? (last - prev) : (last * 2);
    // 추가할 값을 결정하는 조건식

    int[] answer = new int[size + 1];  // 결과 배열 선언, 원본 배열의 길이보다 1 크게 만듦

    for (int i = 0; i < size; i++) {
        answer[i] = num_list[i];  // 원본 배열의 요소를 결과 배열로 복사
    }

    answer[size] = additionalValue;  // 결과 배열의 마지막 요소에 새로운 값을 추가
    // size는 num_list의 길이, answer[size]는 결과 배열의 마지막 위치를 나타냄!!

    return answer;
}

 

3. 다른 풀이

class Solution {
    public int[] solution(int[] num_list) {
        // 결과 배열을 생성, 원본 배열의 길이보다 1 크게 만듦
        int[] answer = new int[num_list.length + 1];

        // 원본 배열의 요소를 결과 배열로 복사
        for (int i = 0; i < num_list.length; i++) {
            answer[i] = num_list[i];
        }

        // 마지막 원소와 그 전 원소를 변수에 저장
        int last = num_list[num_list.length - 1];
        int before = num_list[num_list.length - 2];

        // 마지막 원소가 그 전 원소보다 큰 경우, 결과 배열의 마지막 요소에 (마지막 원소 - 그 전 원소)를 설정
        // 그렇지 않은 경우 결과 배열의 마지막 요소에 (마지막 원소 * 2)를 설정
        answer[answer.length - 1] = (last > before) ? (last - before) : (last * 2);

        // 결과 배열을 반환합니다.
        return answer;
    }
}
class Solution {
    public int[] solution(int[] num_list) {
        // 결과 배열을 생성, 원본 배열의 길이보다 1 크게 만든다
        int[] answer = new int[num_list.length + 1];

        // 원본 배열의 요소를 결과 배열로 복사
        for (int i = 0; i < num_list.length; i++) {
            answer[i] = num_list[i];
        }

        // 마지막 두 원소를 비교, 조건에 따라 결과 배열의 마지막 요소에 값을 설정
        answer[num_list.length] = (num_list[num_list.length - 1] > num_list[num_list.length - 2]) ? 
                                 (num_list[num_list.length - 1] - num_list[num_list.length - 2]) : 
                                 (num_list[num_list.length - 1] * 2);

        // 결과 배열을 반환
        return answer;
    }

System.arraycopy 라는 배열 복사를 수행하는 메서드가 있었다..!

를 사용하면 배열을 효율적으로 복사할 수 있으며, 복사 대상 배열의 크기나 원본 배열의 크기가 달라도 사용할 수 있습니다. 이 메서드를 사용하면 루프를 사용하여 직접 배열 요소를 복사하는 작업을 간소화할 수 있습니다.