-
Notifications
You must be signed in to change notification settings - Fork 21
/
pigeonhole.rs
54 lines (43 loc) · 1.28 KB
/
pigeonhole.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
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl Solution {
pub fn find_duplicates(nums: Vec<i32>) -> Vec<i32> {
let mut nums = nums;
for i in 0..nums.len() {
let mut num = nums[i];
let expected = i as i32 + 1;
while num != expected {
let j = (num - 1) as _;
let target = nums[j];
if num == target {
break;
}
nums.swap(i, j);
num = target;
}
}
(1..=nums.len() as _)
.filter_map(|i| {
let num = nums[(i - 1) as usize];
if num == i {
None
} else {
Some(num)
}
})
.collect()
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn find_duplicates(nums: Vec<i32>) -> Vec<i32> {
Self::find_duplicates(nums)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}