-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_the_duplicate_number.rs
61 lines (50 loc) · 1.38 KB
/
find_the_duplicate_number.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/// Given an array of integers `nums` contains `n + 1` integers where each integer is in the range
/// `[1,n]` inclusive.
///
/// There is only one repeated number in `nums`, return this repeated number.
///
/// You must solve the problem without modifying the array `nums` and uses only constant extra
/// space.
struct Solution;
impl Solution {
pub fn find_duplicate(nums: Vec<i32>) -> i32 {
let mut tortoise = nums[0];
let mut hare = nums[0];
loop {
tortoise = nums[tortoise as usize];
hare = nums[hare as usize];
hare = nums[hare as usize];
if tortoise == hare {
break;
}
}
tortoise = nums[0];
while tortoise != hare {
tortoise = nums[tortoise as usize];
hare = nums[hare as usize];
}
hare
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let nums = vec![1,3,4,2,2];
let result = Solution::find_duplicate(nums);
assert_eq!(result, 2);
}
#[test]
fn example_2() {
let nums = vec![3,1,3,4,2];
let result = Solution::find_duplicate(nums);
assert_eq!(result, 3);
}
#[test]
fn real_world() {
let nums = vec![2,2,2,2,2];
let result = Solution::find_duplicate(nums);
assert_eq!(result, 2);
}
}