[Programmers] 마지막 두 원소 / 기존 배열에 추가하기

dlrmawn·2023년 12월 4일
0

Java

목록 보기
5/16

🔍 문제


📄 입출력 예


⚙️ 정답코드

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;
    }
}


🤔 풀이

answer에 대한 새로운 배열을 만들어주었다.
num_list에 한자리를 추가해야했기에 num_list.length에 + 1을 함

for문으로 기존에 num_list에 대한 값을 불러왔다.
(이 과정을 안해서 초기에 0, 0, 0, 5] 이런식으로 기존 배열 없이 추가 값만 구현되었음ㅜ)

조건문을 통해 answer배열에 마지막 자리를 지정해주었다.

profile
수정해야 할 내용 있으면 메일 부탁드립니다! ⍥

0개의 댓글