-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontains_dup.py
More file actions
46 lines (24 loc) · 1.12 KB
/
Copy pathcontains_dup.py
File metadata and controls
46 lines (24 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
# Example 1:
# Input: nums = [1, 2, 3, 3]
# Output: true
# Example 2:
# Input: nums = [1, 2, 3, 4]
# Output: false
# Topics
# Recommended Time & Space Complexity
# You should aim for a solution with O(n) time and O(n) space, where n is the size of the input array.
# Hint 1
# A brute force solution would be to check every element against every other element in the array. This would be an O(n^2) solution. Can you think of a better way?
# Hint 2
# Is there a way to check if an element is a duplicate without comparing it to every other element? Maybe there's a data structure that is useful here.
# Hint 3
# We can use a hash data structure like a hash set or hash map to store elements we've already seen. This will allow us to check if an element is a duplicate in constant time.
class Solution:
def hasDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False