Skip to content

Commit 026a4ec

Browse files
committed
Improve solution analysis for Contains Duplicate problem
1 parent 601e211 commit 026a4ec

File tree

1 file changed

+12
-26
lines changed

1 file changed

+12
-26
lines changed

โ€Žcontains-duplicate/KwonNayeon.pyโ€Ž

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,23 @@
11
"""
2-
Title: 217. Contains Duplicate
3-
Link: https://leetcode.com/problems/contains-duplicate/
2+
Problem: 217. Contains Duplicate
43
5-
Summary:
6-
- ์ฃผ์–ด์ง„ ๋ฐฐ์—ด `nums`์—์„œ ์–ด๋–ค ๊ฐ’์ด ํ•œ ๋ฒˆ ์ด์ƒ ๋“ฑ์žฅํ•˜๋ฉด True๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , ๋ฐฐ์—ด์˜ ๋ชจ๋“  ๊ฐ’์ด ์œ ์ผํ•œ ๊ฒฝ์šฐ์—๋Š” False๋ฅผ ๋ฐ˜ํ™˜ํ•จ
7-
- Input: `nums = [1,2,3,1]`
8-
- Output: `True`
4+
Constraints:
5+
- 1 <= nums.length <= 10^5
6+
- -10^9 <= nums[i] <= 10^9
97
10-
Conditions:
11-
- ์ค‘๋ณต์ด ์žˆ์œผ๋ฉด: ๋ฐฐ์—ด์—์„œ ์ ์–ด๋„ ํ•˜๋‚˜์˜ ๊ฐ’์ด ๋‘ ๋ฒˆ ์ด์ƒ ๋“ฑ์žฅํ•˜๋ฉด `True` ๋ฐ˜ํ™˜
12-
- ์ค‘๋ณต์ด ์—†์œผ๋ฉด: ๋ฐฐ์—ด์˜ ๋ชจ๋“  ๊ฐ’์ด ์œ ์ผํ•˜๋ฉด `False` ๋ฐ˜ํ™˜
13-
"""
8+
Time Complexity: O(n)
9+
- ๋ฐฐ์—ด์„ ํ•œ ๋ฒˆ๋งŒ ์ˆœํšŒํ•จ
10+
- ์ง‘ํ•ฉ์—์„œ ๊ฒ€์ƒ‰๊ณผ ์ถ”๊ฐ€ ์—ฐ์‚ฐ์€ ํ‰๊ท ์ ์œผ๋กœ O(1)
11+
- ์ด n๊ฐœ ์š”์†Œ์— ๋Œ€ํ•ด ๊ฐ๊ฐ O(1) ์—ฐ์‚ฐ ์ˆ˜ํ–‰
1412
15-
"""
16-
First Try
17-
Time Complexity:
18-
- O(n) * O(n) = O(n^2): `for` ๋ฃจํ”„์—์„œ `nums.count(i)`๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ๋งˆ๋‹ค ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฏ€๋กœ, ์ „์ฒด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” `O(n^2)`
19-
"""
20-
class Solution:
21-
def containsDuplicate(self, nums: List[int]) -> bool:
22-
for i in nums:
23-
if nums.count(i) > 1:
24-
return True
25-
return False
26-
27-
"""
28-
Second Try (set๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ด๋ฏธ ๋ณธ ์š”์†Œ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ์ถ”์ ํ•˜๋Š” ๋ฐฉ๋ฒ•)
29-
Time Complexity:
30-
- O(n): `for` ๋ฃจํ”„์—์„œ ๊ฐ ์ˆซ์ž์— ๋Œ€ํ•ด `in` ์—ฐ์‚ฐ๊ณผ `add` ์—ฐ์‚ฐ์ด ์ƒ์ˆ˜ ์‹œ๊ฐ„ O(1)์œผ๋กœ ์ฒ˜๋ฆฌ๋˜๋ฏ€๋กœ, ์ „์ฒด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n)
13+
Space Complexity: O(n)
14+
- ์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ชจ๋“  ์š”์†Œ๋ฅผ ์ง‘ํ•ฉ์— ์ €์žฅ
15+
- ์ถ”๊ฐ€ ๊ณต๊ฐ„์ด ์ž…๋ ฅ ๋ฐฐ์—ด ํฌ๊ธฐ์— ๋น„๋ก€ํ•จ
3116
"""
3217
class Solution:
3318
def containsDuplicate(self, nums: List[int]) -> bool:
3419
seen = set()
20+
3521
for i in nums:
3622
if i in seen:
3723
return True

0 commit comments

Comments
ย (0)