Skip to content

Commit 5ad248f

Browse files
committed
better solution of Find The Duplicate Number
1 parent 67ca04a commit 5ad248f

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed
Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,34 @@
11
# Find The Duplicate Number
2-
We can solve this problem by Binary Search
2+
We can solve this problem by Binary Search. The better solution is using double pointer like below:
3+
```python
4+
class Solution(object):
5+
def findDuplicate(self, nums):
6+
"""
7+
:type nums: List[int]
8+
:rtype: int
9+
"""
10+
# The "tortoise and hare" step. We start at the end of the array and try
11+
# to find an intersection point in the cycle.
12+
slow = 0
13+
fast = 0
14+
15+
# Keep advancing 'slow' by one step and 'fast' by two steps until they
16+
# meet inside the loop.
17+
while True:
18+
slow = nums[slow]
19+
fast = nums[nums[fast]]
20+
21+
if slow == fast:
22+
break
23+
24+
# Start up another pointer from the end of the array and march it forward
25+
# until it hits the pointer inside the array.
26+
finder = 0
27+
while True:
28+
slow = nums[slow]
29+
finder = nums[finder]
30+
31+
# If the two hit, the intersection index is the duplicate element.
32+
if slow == finder:
33+
return slow
34+
```

0 commit comments

Comments
 (0)