반응형
문제 설명
정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.
제한사항
2 ≤ num_list의 길이 ≤ 10
1 ≤ num_list의 원소 ≤ 9
입출력 예
num_list | result |
[2, 1, 6] | [2, 1, 6, 5] |
[5, 2, 1, 7, 5] | [5, 2, 1, 7, 5, 10] |
입출력 예 설명
입출력 예 #1
마지막 원소인 6이 그전 원소인 1보다 크기 때문에 6 - 1인 5를 추가해 return합니다.
입출력 예 #2
마지막 원소인 5가 그전 원소인 7보다 크지 않기 때문에 5의 두 배인 10을 추가해 return합니다.
class Solution {
public int[] solution(int[] num_list) {
int[] answer = new int[num_list.length+1];
System.arraycopy(num_list, 0, answer, 0, num_list.length);
if(num_list[num_list.length-1] > num_list[num_list.length-2]) {
answer[answer.length-1] = num_list[num_list.length-1] - num_list[num_list.length-2];
} else {
answer[answer.length-1] = num_list[num_list.length-1] * 2;
}
return answer;
}
}
public static int[] solution(int[] num_list) {
int[] answer = new int[num_list.length+1];
System.out.println("111 : " +answer.length);
// answer = num_list; // 이렇게 하면 answer 배열의 크기가 3으로 변경됨
System.arraycopy(num_list, 0, answer, 0, num_list.length); // answer에 num_list의 크기만큼 복사
for(int t : answer) System.out.println("answer : " + t);
if(num_list[num_list.length-1] > num_list[num_list.length-2]) { // 마지막 원소와 바로앞의 원소의 크기를 비교
answer[answer.length-1] = num_list[num_list.length-1] - num_list[num_list.length-2];
} else {
answer[answer.length-1] = num_list[num_list.length-1] * 2;
}
for(int t : answer) System.out.println("answer : "+ t);
return answer;
}
int[] answer = new int[num_list.length+1];
- num_list의 크기+1 만큼의 사이즈로 크기 할당
System.arraycopy(num_list, 0, answer, 0, num_list.length);
- answer에 num_list의 크기만큼 복사
- 복사 후 answer = {2, 1, 6, 0}
반응형
'코딩테스트 > JAVA' 카테고리의 다른 글
[프로그래머스/JAVA] 나머지가 1이 되는 수 찾기 (1) | 2024.04.17 |
---|---|
[프로그래머스/JAVA] 수 조작하기 1 (1) | 2024.04.17 |
[프로그래머스/JAVA] 등차수열의 특정한 항만 더하기 (1) | 2024.04.17 |
[프로그래머스/JAVA] 이어 붙인 수 (1) | 2024.04.17 |
[프로그래머스/JAVA] 원소들의 곱과 합 (1) | 2024.04.17 |