Skip to content

Commit f15e4b4

Browse files
author
0x01f7
committed
solve: Find the Duplicate Number
1 parent a7a4433 commit f15e4b4

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
| 290 | [Word Pattern][p290] | [Ruby][s290] | Easy |
1313
| 289 | [Game of Life][p289] | [Ruby][s289] | Medium |
1414
| 288 | [Unique Word Abbreviation][p288] | :lock: | Easy |
15-
| 287 | [Find the Duplicate Number][p287] | | Hard |
15+
| 287 | [Find the Duplicate Number][p287] | [Ruby][s287] | Hard |
1616
| 286 | [Walls and Gates][p286] | :lock: | Medium |
1717
| 285 | [Inorder Successor in BST][p285] | :lock: | Medium |
1818
| 284 | [Peeking Iterator][p284] | :soon: | Medium |
@@ -570,6 +570,7 @@
570570
[s292]:./algorithms/nim_game.rb
571571
[s290]:./algorithms/word_pattern.rb
572572
[s289]:./algorithms/game_of_life.rb
573+
[s287]:./algorithms/find_the_duplicate_number.rb
573574
[s283]:./algorithms/move_zeroes.rb
574575
[s282]:./algorithms/expression_add_operators.rb
575576
[s279]:./algorithms/perfect_squares.rb
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# https://leetcode.com/problems/find-the-duplicate-number/
2+
#
3+
# Given an array nums containing n + 1 integers where each integer is
4+
# between 1 and n (inclusive), prove that at least one duplicate
5+
# number must exist. Assume that there is only one duplicate number,
6+
# find the duplicate one.
7+
#
8+
# Note:
9+
#
10+
# + You must not modify the array (assume the array is read only).
11+
# + You must use only constant, O(1) extra space.
12+
# + Your runtime complexity should be less than O(n2).
13+
# + There is only one duplicate number in the array, but it could
14+
# be repeated more than once.
15+
16+
17+
# @param {Integer[]} nums
18+
# @return {Integer}
19+
def find_duplicate(nums)
20+
start = nums.size
21+
22+
fast, slow = start, start
23+
loop do
24+
fast = nums[nums[fast - 1] - 1]
25+
slow = nums[slow - 1]
26+
break if fast == slow
27+
end
28+
29+
slow = start
30+
loop do
31+
fast = nums[fast - 1]
32+
slow = nums[slow - 1]
33+
break if fast == slow
34+
end
35+
36+
fast
37+
end

0 commit comments

Comments
 (0)