Post

[Programmers] #181927 - 마지막 두 원소 [Java][C++][Python]

[Programmers] #181927 - 마지막 두 원소 [Java][C++][Python]

문제 링크


1. 아이디어

마지막 원소가 그전 원소보다 클 때만 둘의 차를 붙이고, 그렇지 않으면 마지막 원소의 두 배를 붙인다. 두 값이 같은 경우도 그렇지 않은 쪽에 들어가므로 차인 0이 아니라 두 배를 붙인다.


2. 코드

풀이 [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;
    }
}

배열은 길이를 늘릴 수 없어 Arrays.copyOf로 한 칸 더 큰 배열을 만들고 마지막 칸을 채웠다.

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.