[Programmers] #181840 - 정수 찾기 [Java][C++][Python]
[Programmers] #181840 - 정수 찾기 [Java][C++][Python]
1. 아이디어
정수 리스트 num_list 안에 정수 n이 존재하는지 비교만 하면 되는 간단한 문제다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = num_list의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
class Solution {
public int solution(int[] num_list, int n) {
for (int x : num_list) {
if (x == n) return 1;
}
return 0;
}
}
1
2
3
4
5
6
#include <bits/stdc++.h>
using namespace std;
int solution(vector<int> num_list, int n) {
return find(num_list.begin(), num_list.end(), n) != num_list.end();
}
std::find를 활용해 n을 찾을 수 있다. 반환된 이터레이터가 벡터의 끝이면 n이 존재하지 않는 것이고 끝이 아니면 존재하는 것이다.
1
2
def solution(num_list, n):
return int(n in num_list)
in 연산자로 간단하게 구할 수 있다.
This post is licensed under CC BY 4.0 by the author.