Notice
Recent Posts
Recent Comments
Link
«   2026/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
관리 메뉴

luke

[프로그래머스] - 마지막 두 원소 (Java/자바) 본문

알고리즘문제/프로그래머스(Java)

[프로그래머스] - 마지막 두 원소 (Java/자바)

luke-king 2025. 10. 21. 19:46

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

 

 

 

 

 

 

 

 

문제.


 

 

 

 

 

 

 

 

풀이.


class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length + 1];
        int last = num_list[num_list.length - 1];
        int last2 = num_list[num_list.length - 2];
        
        for(int i = 0; i < num_list.length; i++){
            answer[i] = num_list[i];
        }
        
         
        if(last > last2){
            answer[num_list.length] = last - last2;
        }else{
           answer[num_list.length] = last * 2;
        }
        
        return answer;
    }
}

이번 문제는 프로그래머스 "마지막 두 원소" 문제다.

바로 풀이해보겠다.

 

1. last, last2의 각 변수에 num_list [] 배열에 있는 마지막 인덱스 값과 그전 값을 담아준다.

 

2. for문으로 answe [] 배열에 num_list[] 값을 넣어준다. 여기서 answer[]의 길이는 마지막에 인덱스를 추가해줘야 하기에 num_list.length + 1을 해준다.

 

3. 마지막으로 배열에 있는 마지막 인덱스 값이 전 인덱스 값보다 크면 last - last2를 해주고
그렇지 않다면 last *2를 해주면 끝이다.