Skip to content

Commit 36e352a

Browse files
committed
Create find-the-duplicate-number.py
1 parent 87b06ba commit 36e352a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def findDuplicate(self, nums):
6+
"""
7+
:type nums: List[int]
8+
:rtype: int
9+
"""
10+
duplicate = 0
11+
# Mark the value as visited by negative.
12+
for num in nums:
13+
if nums[abs(num) - 1] > 0:
14+
nums[abs(num) - 1] *= -1
15+
else:
16+
duplicate = abs(num)
17+
break
18+
# Rollback the value.
19+
for num in nums:
20+
if nums[abs(num) - 1] < 0:
21+
nums[abs(num) - 1] *= -1
22+
else:
23+
break
24+
return duplicate

0 commit comments

Comments
 (0)