Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions contains-duplicate/hi-rachel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
https://leetcode.com/problems/contains-duplicate/

Given an integer array nums,
return true if any value appears at least twice in the array,
and return false if every element is distinct.

TC: O(n)
SC: O(n)
"""

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

16줄의 seen = set() 방식은 하나씩 돌면서 바로 중복을 체크하는 방식이고,
28줄의 len(set(nums)) != len(nums) 방식은 전체 리스트를 한 번에 변환해 길이로 비교하는 방식입니다.
두 가지 방법을 함께 볼 수 있어서 이해하는 데 많은 분들에게 큰 도움이 될 것 같습니다!

from typing import List

class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()

for num in nums:
if num in seen:
return True
else:
seen.add(num)
Comment on lines +21 to +22
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

바로 True를 리턴해주니까, else:는 없어도 될 것 같아요!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hyunjung-choi
num을 set에 넣지 않으면 seen 체크를 할 수가 없는데 (숫자를 이미 봤음)
혹시 더 설명해주실 수 있나요?

Copy link
Member

@hyunjung-choi hyunjung-choi Jul 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hi-rachel 아 저 뜻은 else:없이 바로

for num in nums:
    if num in seen:
        return True
    seen.add(num)
return False

이렇게 해도 될 것 같다는 뜻이었습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hyunjung-choi 굳이 else를 쓰지 않아도 된다는 말씀이셨군요. 그렇네요. 감사합니다!

return False


class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) != len(nums)