Skip to content

Commit 3bce933

Browse files
committed
solve(w01): 217. Contains Duplicate
1 parent f291ae8 commit 3bce933

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# https://leetcode.com/problems/contains-duplicate/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def containsDuplicate1(self, nums: List[int]) -> bool:
7+
"""
8+
[Complexity]
9+
- TC: O(n) (set(nums) ์‹œ ์›์†Œ๋ฅผ ๋ณต์‚ฌํ•˜๋Š” ๋ฐ์— O(n), len()์€ O(1))
10+
- SC: O(n)
11+
12+
[Approach]
13+
set(hash map)์„ ์ด์šฉํ•˜์—ฌ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•œ ๊ฒฐ๊ณผ์˜ ๊ธธ์ด๋ฅผ ์›๋ณธ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด์™€ ๋น„๊ตํ•˜๋ฉด ๋œ๋‹ค.
14+
"""
15+
16+
return len(nums) != len(set(nums))
17+
18+
19+
def containsDuplicate(self, nums: List[int]) -> bool:
20+
"""
21+
[Complexity]
22+
- TC: O(n) (iteration)
23+
- SC: O(n)
24+
25+
[Approach]
26+
nums๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ set(hash map)์— ๋“ฑ์žฅํ–ˆ๋˜ ์›์†Œ๋ฅผ add ํ•˜๊ณ , ๋™์ผํ•œ ์›์†Œ๊ฐ€ ๋ฐœ๊ฒฌ๋˜๋ฉด True๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
27+
nums ์ „์ฒด๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋™์ผํ•œ ์›์†Œ๊ฐ€ ์—†์—ˆ๋‹ค๋ฉด False๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
28+
"""
29+
30+
seen = set()
31+
32+
for num in nums: # -- O(n)
33+
if num in seen: # -- O(1)
34+
return True
35+
seen.add(num)
36+
37+
return False

0 commit comments

Comments
ย (0)