Skip to content

Commit 8d9e45c

Browse files
solves find the duplicate element #287 in java
1 parent dcf5224 commit 8d9e45c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@
234234
| 284 | [Peeking Iterator](https://leetcode.com/problems/peeking-iterator) | [![Java](assets/java.png)](src/PeekingIterator.java) | |
235235
| 285 | 🔒 [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst) | | |
236236
| 286 | 🔒 [Walls and Gates](https://leetcode.com/problems/walls-and-gates) | | |
237-
| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number) | | |
237+
| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number) | [![Java](assets/java.png)](src/FindTheDuplicateNumber.java) | |
238238
| 288 | 🔒 [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation) | | |
239239
| 289 | [Game of Life](https://leetcode.com/problems/game-of-life) | | |
240240
| 290 | [Word Pattern](https://leetcode.com/problems/word-pattern) | [![Java](assets/java.png)](src/WordPattern.java) [![Python](assets/python.png)](python/word_pattern.py) | |

src/FindTheDuplicateNumber.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/find-the-duplicate-number
2+
// T: O(N)
3+
// S: O(1)
4+
5+
public class FindTheDuplicateNumber {
6+
public static int findDuplicate(int[] nums) {
7+
int tortoise = nums[0];
8+
int hare = nums[0];
9+
10+
do {
11+
tortoise = nums[tortoise];
12+
hare = nums[nums[hare]];
13+
} while (tortoise != hare);
14+
15+
// Find the "entrance" to the cycle.
16+
tortoise = nums[0];
17+
18+
while (tortoise != hare) {
19+
tortoise = nums[tortoise];
20+
hare = nums[hare];
21+
}
22+
23+
return hare;
24+
}
25+
}
26+

0 commit comments

Comments
 (0)