
์๊ฐ ๋ฐฉ์
Empty ๋ฆฌ์คํธ๋ฅผ ํ๋ ๋ง๋ค์ด์ ๊ทธ ์์ ํน์ ์ค๋ณต๋ value๊ฐ ์๋์ง ํ์ธํ๊ณ , ์์ผ๋ฉด True, ์๋ค๋ฉด False๋ก ํ๋ฉด ๋ ๊ฒ ๊ฐ๋ค.
๐ป ์ฝ๋
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
a = []
for num in nums:
if num in a:
return True
a.append(num)
return False
Time Complexity: O(n^2)
์๊ฐ ๋ณต์ก๋๊ฐ ๋๊ธฐ์ ๋ค๋ฅธ ํด๊ฒฐ ๋ฐฉ์์ ์๊ฐํด ๋ณด์๋ค
๋ค๋ฅธ ๋ฐฉ๋ฒ์ set()์ ์ฌ์ฉํ๋ ๊ฒ์ด๋ค.
"In Python, sets have an algorithmic complexity of O(1) for average case time complexity for common operations like adding, removing, and checking for membership."
๊ทธ๋์ ์ด๋ฐ ์ผ์ด์ค์์ loop์ ์ฌ์ฉํ๋ค๋ฉด O(n)์ด ๋๋ค.
๐ป ์ฝ๋
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
s = set()
for num in nums:
if num in s:
return True
s.add(num)
return False
์ด ๊ธ์ ์์ฑํ๋ฉด์ ์ข ๋ ๊ฐ๊ฒฐํ ์ฝ๋๋ฅผ ์ฐพ์๋ค
(https://velog.io/@datawhales/Problem-Solving-with-Python-LeetCode-217.-Contains-Duplicate)
class Solution:
def containsDuplicate_2(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))

'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 746. Min Cost Climbing Stairs (Easy) [Python] (0) | 2024.02.04 |
|---|---|
| 70. Climbing Stairs (Easy) [Python] (2) | 2024.02.03 |
| 49. Group Anagrams (Medium) [Python] (0) | 2024.02.03 |
| 1. Two Sum (Easy) [Python] (0) | 2024.02.03 |
| 242. Valid Anagram (Easy) [Python] (0) | 2024.02.03 |