File tree 1 file changed +33
-1
lines changed
algorithms/FindTheDuplicateNumber
1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change 1
1
# 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
+ ```
You can’t perform that action at this time.
0 commit comments