-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0287-find-the-duplicate-number.py
More file actions
37 lines (31 loc) · 874 Bytes
/
0287-find-the-duplicate-number.py
File metadata and controls
37 lines (31 loc) · 874 Bytes
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
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
fast = slow = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return fast
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)
nums = [1, 3, 4, 2, 2]
print(Solution().findDuplicate(nums))
nums = [3, 1, 3, 4, 2]
print(Solution().findDuplicate(nums))
nums = [3, 3, 3, 3, 3]
print(Solution().findDuplicate(nums))