[Programmers] 181927번 - 마지막 두 원소 [Java][C++]
[Programmers] 181927번 - 마지막 두 원소 [Java][C++]
1. 아이디어
정수 리스트 num_list에 대해 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을, 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하려 return하는 문제로 인덱스를 통해 특정 위치의 원소에 접근할 수 있으면 해결할 수 있다.
2. 복잡도
| 시간복잡도 | 공간복잡도 |
|---|---|
| $O(N)$ | $O(1)$ |
$N$ =
num_list길이
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] solution(int[] num_list) {
int[] ans = new int[num_list.length + 1];
for (int i = 0; i < num_list.length; i++) {
ans[i] = num_list[i];
}
int a = num_list[num_list.length - 2];
int b = num_list[num_list.length - 1];
if (b > a) {
ans[ans.length - 1] = b - a;
} else {
ans[ans.length - 1] = b * 2;
}
return ans;
}
}
기존 num_list 뒤에 바로 추가하는 방식으로 구현했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> num_list) {
int a = num_list[num_list.size() - 2];
int b = num_list[num_list.size() - 1];
if (b > a) {
num_list.push_back(b - a);
} else {
num_list.push_back(b * 2);
}
return num_list;
}
This post is licensed under CC BY 4.0 by the author.