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
'Algorithm' 카테고리의 다른 글
[프로그래머스] (181925) 수 조작하기2 (0) | 2023.12.24 |
---|---|
[프로그래머스] (181926) 수 조작하기1 (0) | 2023.12.24 |
[프로그래머스] (181928) 이어 붙인 수 (1) | 2023.12.24 |
[프로그래머스] (181932) 코드 처리하기 (0) | 2023.12.23 |
[백준](15552) 빠른 A+B (0) | 2023.12.19 |