[코딩테스트] 38. 마지막 두 원소

편준민's avatar
Apr 29, 2025
[코딩테스트] 38. 마지막 두 원소

문제

💡
정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.

제한사항

  • 2 ≤ num_list의 길이 ≤ 10
  • 1 ≤ num_list의 원소 ≤ 9

예시

notion image

풀이

기존 list[]에는 추가로 숫자를 추가 할 수 없기 때문에 ArrayList를 만들어서 num_list[]를 옮겨주었다. 이후 조건식에 맞게 배열의 마지막 원소와, 그 전 원소만 가지고 오기 위해서 num_list.length - 1 를 사용하였고, 바로 list.add 를 사용하여 배열에 추가하여 주었다.
print를 사용하여 출력은 되지만 코딩테스트에서는 return을 해주어야하기 때문에 계속해서 에러가 났다. 이유는 List<Integer>를 바로int[]로 리턴할 수 없었기 때문이다. 그렇기 때문에 List<Integer>를 다시 int[]로 변환하여 리턴해서 통과하였다.
int num_list[] = {2, 1, 6}; int lastnum = 0; List<Integer> list = new ArrayList<>(); for (int num : num_list) { list.add(num); } if (num_list[num_list.length - 1] > num_list[num_list.length - 2]) { lastnum = num_list[num_list.length - 1] - num_list[num_list.length - 2]; list.add(lastnum); } else { lastnum = num_list[num_list.length - 1] * 2; list.add(lastnum); } int[] result = new int[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); // Integer → int 자동 언박싱 } System.out.println(result);
notion image
통과는 하였지만 이렇게까지 복잡한 문제일까? 싶어서 다른 사람의 풀이를 찾아보았다. 아래의 코드는 다른 사람의 코드이다. 나는 list[]에 추가를 못할 거라고 생각하여 ArrayList<>를 사용하였는데, list[]를 새롭게 1칸 늘려서 만드는 방식이 있다는 것을 알았다. 이렇게 주소를 한 칸 늘려서 만들면 return도 바로 해줄 수 있기 때문에 이 방법이 더 복잡하지 않은 것 같다.
int[] answer = new int[num_list.length+1]; for(int i=0; i<num_list.length; i++){ answer[i] = num_list[i]; } answer[num_list.length] = num_list[num_list.length-1] > num_list[num_list.length-2] ? num_list[num_list.length-1]-num_list[num_list.length-2]:num_list[num_list.length-1]*2; return answer;
Share article

YunSeolAn