Skip to content

Commit 191c61c

Browse files
authored
Merge pull request #850 from t3chkid/main
Adds solution for 287. Find the Duplicate Number in Kotlin
2 parents a3e3549 + 31a8642 commit 191c61c

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package kotlin
2+
3+
class Solution {
4+
fun findDuplicate(nums: IntArray): Int {
5+
var slow = 0
6+
var slow2 = 0
7+
var fast = 0
8+
// detect the cycle
9+
while (true) {
10+
slow = nums[slow]
11+
fast = nums[nums[fast]]
12+
if (slow == fast) break
13+
}
14+
// get the first value at the beginning of the cycle
15+
while (true) {
16+
slow2 = nums[slow2]
17+
slow = nums[slow]
18+
if (slow2 == slow) return slow
19+
}
20+
}
21+
}

0 commit comments

Comments
 (0)