-
프로그래머스 Lv0 - 마지막 두 원소알고리즘공부 2024. 3. 6. 22:51728x90
1. 문제 설명
- 정수 리스트 num_list 가 주어질 때 , 마지막 원소가 그전 원소보다 크면 마지막 원소가에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return 하도록 함수를 완성해주세요.
2. 제한사항
- 2 <= num_list 의 길이 <= 10
- 1 <= num_list 의 원소 <= 9
3. 입출력 예
4. 내가 작성한 코드
class Solution { public int[] solution(int[] num_list) { int[] answer = new int[(num_list.length + 1)]; for(int i = 0; i < num_list.length; i++){ answer[i] = num_list[i]; } if(num_list[(num_list.length)] > num_list[(num_list.length - 1)]){ answer[num_list.length] = num_list[(num_list.length)] - num_list[(num_list.length - 1)]; } else { answer[num_list.length] = num_list[(num_list.length)] * 2; } return answer; } }
ArrayIndexOutOfBoundsException 오류를 보고 나서 배열 범위를 생각해보던 중 내가 계산 했던 것들보다 -1을 더 해줘야 한다는 것을 깨달았다..
5. 수정한 코드
class Solution { public int[] solution(int[] num_list) { int[] answer = new int[(num_list.length + 1)]; 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; } }
'알고리즘공부' 카테고리의 다른 글
프로그래머스 Lv0 - 수열과 구간 쿼리 3 (0) 2024.03.18 프로그래머스 Lv0 - 수 조작하기 2 (0) 2024.03.07 프로그래머스 Lv0 - 더 크게 합치기 (1) 2024.03.06 프로그래머스 Lv0 - 문자열 섞기 (0) 2024.03.05 프로그래머스 Lv0 - 문자열 겹쳐쓰기 (0) 2024.03.05