-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_number_iii.rs
68 lines (59 loc) · 1.87 KB
/
single_number_iii.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
62
63
64
65
66
67
68
use std::collections::BTreeSet;
// Time: O(n)
// Space: O(1)
pub struct Solution1 {}
impl Solution1 {
pub fn single_number(nums: Vec<i32>) -> Vec<i32> {
// Xor all the elements to get x ^ y.
let x_xor_y: i32 = nums.iter().fold(0, |acc, &num| acc ^ num);
// Get the last bit where 1 occurs by "x & ~(x - 1)"
// Because -(x - 1) = ~(x - 1) + 1 <=> -x = ~(x - 1)
// So we can also get the last bit where 1 occurs by "x & -x"
let bit: i32 = x_xor_y & -x_xor_y;
let mut result = vec![0; 2];
nums.iter()
.for_each(|i| result[((i & bit) != 0) as usize] ^= i);
result
}
}
pub struct Solution2 {}
impl Solution2 {
pub fn single_number(nums: Vec<i32>) -> Vec<i32> {
// Xor all the elements to get x ^ y.
let mut x_xor_y: i32 = 0;
for i in nums.iter() {
x_xor_y ^= i;
}
// Get the last bit where 1 occurs.
let bit: i32 = x_xor_y & -x_xor_y;
// Get the subset of A where the number has the bit.
// The subset only contains one of the two integers, call it x.
// Xor all the elements in the subset to get x.
let mut x: i32 = 0;
nums.iter().for_each(|i| {
if i & bit != 0 {
x ^= i;
}
});
vec![x, x_xor_y ^ x]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_number() {
assert_eq!(
Solution1::single_number(vec![1, 2, 1, 3, 2, 5])
.into_iter()
.collect::<BTreeSet<i32>>(),
vec![3, 5].into_iter().collect::<BTreeSet<i32>>()
);
assert_eq!(
Solution2::single_number(vec![1, 2, 1, 3, 2, 5])
.into_iter()
.collect::<BTreeSet<i32>>(),
vec![3, 5].into_iter().collect::<BTreeSet<i32>>()
);
}
}