문제 설명
정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.
문제 읽으면서 정리
- num_list = 2, 1, 6이라면 1 < 6
-> 6 - 1 = 5
-> num_list = 2, 1, 6, 5
num_list = 5, 2, 1이라면 2 > 1
-> 1 * 2 = 2
-> num_list = 5, 2, 1, 2 - 먼저 배열을 리스트로 변경한 후 add() 함수를 사용해서 추가해야겠다
틀린 부분
- 리스트를 배열로 변경하는데 arrList.toArray()/
배열을 리스트로 변경하는데 Arrays.asList() 사용
-> int 같은 primitive 타입은 Arrays.asLlist()를 사용할 수 없다
-> 반복문 사용하여 리스트로 변경
List<Integer> list = new ArrayList<>();
for (int num : num_list) {
list.add(num);
}
2. if에서 크다면을 설정했으면 else로 넘어갔어야 한다
첫 번째 조건문이 크다면이고 두 번째 조건문은 '크지 않다면' = 작거나 같다면 으로 해석이 가능하다
import java.util.*;
class Solution {
public int[] solution(int[] num_list) {
List<Integer> list = new ArrayList<>();
for (int num : num_list) {
list.add(num);
}
if(num_list[num_list.length-2] < num_list[num_list.length-1]) {
int last = num_list[num_list.length-1] - num_list[num_list.length-2];
list.add(last);
}
else {
int last = num_list[num_list.length-1]*2;
list.add(last);
}
num_list = list.stream()
.mapToInt(i -> i)
.toArray();
return num_list;
}
}