53
54
kamyu104/src/main.rsCopy file name to clipboard +2 -1 Lines changed: 2 additions & 1 deletion Original file line number Diff line number Diff line change 1
- mod template;
2
1
mod single_number;
2
+ mod single_number_ii;
3
+ mod template;
Original file line number Diff line number Diff line change
1
+ use std:: collections:: HashSet ;
2
+
3
+ pub struct Solution1 { }
4
+ pub struct Solution2 { }
5
+ pub struct Solution3 { }
6
+ pub struct Solution4 { }
7
+
8
+ impl Solution1 {
9
+ pub fn single_number ( nums : Vec < i32 > ) -> i32 {
10
+ let ( mut one, mut two) : ( i32 , i32 ) = ( 0 , 0 ) ;
11
+ for num in nums. iter ( ) {
12
+ let new_one = ( !num & one) | ( num & !one & !two) ;
13
+ let new_two = ( !num & two) | ( num & one) ;
14
+ one = new_one;
15
+ two = new_two;
16
+ }
17
+ one
18
+ }
19
+ }
20
+
21
+ impl Solution2 {
22
+ pub fn single_number ( nums : Vec < i32 > ) -> i32 {
23
+ let ( mut one, mut two, mut carry) : ( i32 , i32 , i32 ) = ( 0 , 0 , 0 ) ;
24
+ for num in nums. iter ( ) {
25
+ two |= one & num;
26
+ one ^= num;
27
+ carry = one & two;
28
+ one &= !carry;
29
+ two &= !carry;
30
+ }
31
+ one
32
+ }
33
+ }
34
+
35
+ // https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/single-number-ii.py#L31
36
+ // impl Solution3 {
37
+ // pub fn single_number(nums: Vec) -> i32 {
38
+ // }
39
+ // }
40
+
41
+ impl Solution4 {
42
+ pub fn single_number ( nums : Vec < i32 > ) -> i32 {
43
+ let sum: i32 = nums. iter ( ) . sum ( ) ;
44
+ let set_sum: i32 = nums. iter ( ) . cloned ( ) . collect :: < HashSet < i32 > > ( ) . iter ( ) . sum ( ) ;
45
+ ( 3 * set_sum - sum) / 2
46
+ }
47
+ }
48
+
49
+ #[ cfg( test) ]
50
+ mod tests {
51
+ use super :: * ;
52
+
53
+ #[ test]
54
+ fn test_add ( ) {
55
+ assert_eq ! ( Solution1 :: single_number( vec![ 2 , 2 , 3 , 2 ] ) , 3 ) ;
56
+ assert_eq ! ( Solution1 :: single_number( vec![ 0 , 1 , 0 , 1 , 0 , 1 , 99 ] ) , 99 ) ;
57
+ assert_eq ! ( Solution1 :: single_number( vec![ 0 , 0 , 0 , 1 , 1 , 1 , 5 ] ) , 5 ) ;
58
+
59
+ assert_eq ! ( Solution2 :: single_number( vec![ 2 , 2 , 3 , 2 ] ) , 3 ) ;
60
+ assert_eq ! ( Solution2 :: single_number( vec![ 0 , 1 , 0 , 1 , 0 , 1 , 99 ] ) , 99 ) ;
61
+ assert_eq ! ( Solution2 :: single_number( vec![ 0 , 0 , 0 , 1 , 1 , 1 , 5 ] ) , 5 ) ;
62
+
63
+ // assert_eq!(Solution3::single_number(vec![2,2,3,2]), 3);
64
+ // assert_eq!(Solution3::single_number(vec![0,1,0,1,0,1,99]), 99);
65
+ // assert_eq!(Solution3::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5);
66
+
67
+ assert_eq ! ( Solution4 :: single_number( vec![ 2 , 2 , 3 , 2 ] ) , 3 ) ;
68
+ assert_eq ! ( Solution4 :: single_number( vec![ 0 , 1 , 0 , 1 , 0 , 1 , 99 ] ) , 99 ) ;
69
+ assert_eq ! ( Solution4 :: single_number( vec![ 0 , 0 , 0 , 1 , 1 , 1 , 5 ] ) , 5 ) ;
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments