[Programmers] #181853 - 뒤에서 5등까지 [Java][C++][Python]
[Programmers] #181853 - 뒤에서 5등까지 [Java][C++][Python]
1. 아이디어
정수로 이루어진 리스트 num_list를 오름차순으로 정렬한 후 앞에서부터 5개를 취하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N \log N)$ | $O(1)$ |
($N$ = num_list의 길이. Python은 sorted()가 길이 $N$짜리 새 리스트를 만들어 반환하므로 공간 $O(N)$)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
import java.util.*;
class Solution {
public int[] solution(int[] num_list) {
Arrays.sort(num_list);
return Arrays.copyOf(num_list, 5);
}
}
1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> num_list) {
sort(num_list.begin(), num_list.end());
return vector<int>(num_list.begin(), num_list.begin() + 5);
}
1
2
def solution(num_list):
return sorted(num_list)[:5]
This post is licensed under CC BY 4.0 by the author.