inblog logo
|
sxias
    Programmers_CT

    [Programmers_CT] 44. 마지막 두 원소

    문정준's avatar
    문정준
    Apr 09, 2025
    [Programmers_CT] 44. 마지막 두 원소
    Contents
    1. 문제 설명2. 입출력 예시3. 코드 작성4. 테스트 실행5. 제출 후 채점
     
    💡
    프로그래머스 코딩 테스트 42. 마지막 두 원소

    1. 문제 설명

    notion image
     

    제한 사항

    notion image

    2. 입출력 예시

    notion image

    3. 코드 작성

    import java.util.*; class Solution { public int[] solution(int[] num_list) { List<Integer> answer = new ArrayList<>(); for (int num : num_list) { answer.add(num); } int index = num_list.length - 1; if (num_list[index] > num_list[index - 1]) { answer.add(num_list[index] - num_list[index - 1]); } else { answer.add(num_list[index] * 2); } int[] result = new int[answer.size()]; for (int i = 0; i < answer.size(); i++) { result[i] = answer.get(i); } return result; } }
    ✏️

    배열 합치기

    • List를 이용해 기존 배열을 합치고, 결과를 마지막에 더해서 배열로 변환하여 출력
      • for (int i = 0; i < answer.size(); i++) { result[i] = answer.get(i); }

    4. 테스트 실행

    notion image

    5. 제출 후 채점

    notion image
     

    Solution

    • new ArrayList(Arrays.asList(num_list))의 오류
      • 생성하는 리스트는 Integer 배열이나, 변환하려는 배열은 int 배열이므로 오류 발생
      • 직접 원소를 for문을 돌리면서 list에 추가하여 해결
    notion image
     
    Share article
    Contents
    1. 문제 설명2. 입출력 예시3. 코드 작성4. 테스트 실행5. 제출 후 채점

    Sxias ㆍ a32176740@gmail.com

    RSS·Powered by Inblog