앞으로 매일 꾸준히 코딩테스트를 진행하면서 단계를 높여가보자.
정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.
2 ≤ num_list의 길이 ≤ 10
1 ≤ num_list의 원소 ≤ 9

class Solution {
public int[] solution(int[] num_list) {
// (마지막 원소가 들어갈) answer 배열 생성
int[] answer = new int[num_list.length + 1];
// 마지막 원소 변수 생성
int last = 0;
// 반복문으로 배열에 하나씩 담아 조건식에 따라 마지막 원소 값을 넣는다.
for (int i=0; i<num_list.length; i++) {
answer[i] = num_list[i];
if (num_list[num_list.length -1] > num_list[num_list.length -2]) {
answer[num_list.length] = num_list[num_list.length -1] - num_list[num_list.length -2];
} else {
answer[num_list.length] = num_list[num_list.length -1] * 2;
}
}
return answer;
}
}
배열의 길이를 통해 index 번호로 그 자리에 위치한 원소를 알 수 있다.