[Programmers] #181927 - 마지막 두 원소 [Java][C++][Python]
[Programmers] #181927 - 마지막 두 원소 [Java][C++][Python]
1. 아이디어
정수 리스트 num_list가 주어질 때, 마지막 원소와 그 이전 원소를 비교해 마지막 원소가 더 크면 두 값의 차를, 그렇지 않으면 마지막 원소의 2배를 리스트 끝에 추가해 반환하면 되는 문제다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(1)$ | $O(1)$ |
($N$ = num_list의 길이. Java는 길이 $N + 1$짜리 배열을 새로 만들어 반환해 시간·공간 $O(N)$)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.*;
class Solution {
public int[] solution(int[] num_list) {
int n = num_list.length;
int[] ans = Arrays.copyOf(num_list, n + 1);
if (num_list[n - 1] > num_list[n - 2]) {
ans[n] = num_list[n - 1] - num_list[n - 2];
} else {
ans[n] = num_list[n - 1] * 2;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> num_list) {
int n = num_list.size();
if (num_list[n - 1] > num_list[n - 2]) {
num_list.push_back(num_list[n - 1] - num_list[n - 2]);
} else {
num_list.push_back(num_list[n - 1] * 2);
}
return num_list;
}
1
2
3
4
5
6
7
def solution(num_list):
if num_list[-1] > num_list[-2]:
num_list.append(num_list[-1] - num_list[-2])
else:
num_list.append(num_list[-1] * 2)
return num_list
This post is licensed under CC BY 4.0 by the author.