-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle_number_ii.rs
73 lines (63 loc) · 2.21 KB
/
single_number_ii.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
69
70
71
72
73
// Time: O(n)
// Space: O(1)
use std::collections::HashSet;
pub struct Solution1 {}
impl Solution1 {
pub fn single_number(nums: Vec<i32>) -> i32 {
let (mut one, mut two): (i32, i32) = (0, 0);
for num in nums.iter() {
let new_one = (!num & one) | (num & !one & !two);
let new_two = (!num & two) | (num & one);
one = new_one;
two = new_two;
}
one
}
}
pub struct Solution2 {}
impl Solution2 {
pub fn single_number(nums: Vec<i32>) -> i32 {
let (mut one, mut two, mut carry): (i32, i32, i32) = (0, 0, 0);
for num in nums.iter() {
two |= one & num;
one ^= num;
carry = one & two;
one &= !carry;
two &= !carry;
}
one
}
}
// https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/single-number-ii.py#L31
// pub struct Solution3 {}
// impl Solution3 {
// pub fn single_number(nums: Vec<i32>) -> i32 {
// }
// }
pub struct Solution4 {}
impl Solution4 {
pub fn single_number(nums: Vec<i32>) -> i32 {
let sum: i32 = nums.iter().sum();
let set_sum: i32 = nums.iter().cloned().collect::<HashSet<i32>>().iter().sum();
(3 * set_sum - sum) / 2
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_number() {
assert_eq!(Solution1::single_number(vec![2, 2, 3, 2]), 3);
assert_eq!(Solution1::single_number(vec![0, 1, 0, 1, 0, 1, 99]), 99);
assert_eq!(Solution1::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5);
assert_eq!(Solution2::single_number(vec![2, 2, 3, 2]), 3);
assert_eq!(Solution2::single_number(vec![0, 1, 0, 1, 0, 1, 99]), 99);
assert_eq!(Solution2::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5);
// assert_eq!(Solution3::single_number(vec![2,2,3,2]), 3);
// assert_eq!(Solution3::single_number(vec![0,1,0,1,0,1,99]), 99);
// assert_eq!(Solution3::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5);
assert_eq!(Solution4::single_number(vec![2, 2, 3, 2]), 3);
assert_eq!(Solution4::single_number(vec![0, 1, 0, 1, 0, 1, 99]), 99);
assert_eq!(Solution4::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5);
}
}