Skip to content

Commit d9e0a71

Browse files
committed
Sync LeetCode submission Runtime - 26 ms (64.72%), Memory - 30.2 MB (24.30%)
1 parent e4d0d1f commit d9e0a71

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p>
2+
3+
<p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p>
4+
5+
<p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [1,3,4,2,2]
12+
<strong>Output:</strong> 2
13+
</pre>
14+
15+
<p><strong class="example">Example 2:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> nums = [3,1,3,4,2]
19+
<strong>Output:</strong> 3
20+
</pre>
21+
22+
<p><strong class="example">Example 3:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> nums = [3,3,3,3,3]
26+
<strong>Output:</strong> 3</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
33+
<li><code>nums.length == n + 1</code></li>
34+
<li><code>1 &lt;= nums[i] &lt;= n</code></li>
35+
<li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li>
36+
</ul>
37+
38+
<p>&nbsp;</p>
39+
<p><b>Follow up:</b></p>
40+
41+
<ul>
42+
<li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li>
43+
<li>Can you solve the problem in linear runtime complexity?</li>
44+
</ul>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 7: Floyd's Tortoise and Hare (Cycle Detection)
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def findDuplicate(self, nums: List[int]) -> int:
8+
# Find the intersection point of the two runners.
9+
slow, fast = 0, 0
10+
while True:
11+
slow = nums[slow]
12+
fast = nums[nums[fast]]
13+
if slow == fast:
14+
break
15+
16+
# Find the "entrance" to the cycle.
17+
slow2 = 0
18+
while slow != slow2:
19+
slow = nums[slow]
20+
slow2 = nums[slow2]
21+
22+
return slow
23+
24+
25+

0 commit comments

Comments
 (0)