Algorithm

[프로그래머스] (181927) 마지막 두 원소

31daylee 2023. 12. 24. 18:03
728x90

 

 

 


 

언어_자바

프로그래머스_마지막 두 원소

 


 

 

 

public class LastTwo {
    public static void main(String[] args) {
        Test3 t = new Test3();
        int[] num_list = {5, 2, 1, 7, 5};
        t.test3(num_list);
    }
}

class Test3{
    public int[] test3(int[] num_list) {
        int[] answer = new int[num_list.length +1]; // 새로운 배열을 생성한다. 중요한 점은 +1 하여 길이를 확장하는 것.
        int last = 0;

        if(num_list[num_list.length-1] > num_list[num_list.length-2] ){
            last = num_list[num_list.length-1] - num_list[num_list.length-2];
        }else{
            last = num_list[num_list.length-1] * 2;
        }

        for (int i = 0; i < num_list.length; i++) {
            answer[i] = num_list[i]; // [5, 2, 1, 7, 5] 가 배열 안에 들어가 있다
        }
        answer[answer.length - 1] = last; // last = 10 을 answer 배열 마지막에 넣어준다.

        return answer;
    }
}

 

 

Key Point는 총 3가지라 볼 수 있다. 

1. int [ ] answer 의 배열의 크기를 마지막 원소가 들어갈 수 있게 +1 확장 시켜둔다. 
2. 기존 원소들의 값 비교는 num_list 에서 주어진 값으로 비교한다. -> num_list.length 사용 중요
3. 마지막 원소(=last)의 값은 answer.length -1 에 넣는다.

 

 

 

 

 

 

728x90