File tree Expand file tree Collapse file tree 2 files changed +39
-1
lines changed Expand file tree Collapse file tree 2 files changed +39
-1
lines changed Original file line number Diff line number Diff line change 12
12
| 290 | [ Word Pattern] [ p290 ] | [ Ruby] [ s290 ] | Easy |
13
13
| 289 | [ Game of Life] [ p289 ] | [ Ruby] [ s289 ] | Medium |
14
14
| 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 |
16
16
| 286 | [ Walls and Gates] [ p286 ] | :lock : | Medium |
17
17
| 285 | [ Inorder Successor in BST] [ p285 ] | :lock : | Medium |
18
18
| 284 | [ Peeking Iterator] [ p284 ] | :soon : | Medium |
570
570
[ s292 ] :./algorithms/nim_game.rb
571
571
[ s290 ] :./algorithms/word_pattern.rb
572
572
[ s289 ] :./algorithms/game_of_life.rb
573
+ [ s287 ] :./algorithms/find_the_duplicate_number.rb
573
574
[ s283 ] :./algorithms/move_zeroes.rb
574
575
[ s282 ] :./algorithms/expression_add_operators.rb
575
576
[ s279 ] :./algorithms/perfect_squares.rb
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments