[LeetCode] #217 - Contains Duplicate [Java][C++][Python]
[LeetCode] #217 - Contains Duplicate [Java][C++][Python]
1. 아이디어
정수 배열 nums에 대해 두 번 이상 등장한 원소가 있으면 true를 아니면 false를 반환하는 문제다. 각 정수의 중복 여부를 판단한다는 점에서 해시 집합을 활용하면 간단하게 해결할 수 있다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = nums의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int x : nums) {
if (!seen.add(x)) return true;
}
return false;
}
}
1
2
3
4
5
6
7
8
9
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return unordered_set(nums.begin(), nums.end()).size() < nums.size();
}
};
1
2
3
class Solution:
def containsDuplicate(self, nums: list[int]) -> bool:
return len(set(nums)) < len(nums)
This post is licensed under CC BY 4.0 by the author.