-
Notifications
You must be signed in to change notification settings - Fork 1
/
137.single-number-ii.rs
52 lines (42 loc) · 972 Bytes
/
137.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
/*
* @lc app=leetcode id=137 lang=rust
*
* [137] Single Number II
*/
// @lc code=start
use std::collections::HashMap;
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
Self::bit_manipulation_sol(nums)
}
pub fn hashmap_sol(nums: Vec<i32>) -> i32 {
let mut map = HashMap::new();
for num in nums {
if let Some(v) = map.get_mut(&num) {
*v += 1;
} else {
map.insert(num, 1);
}
}
for k in &map {
if *k.1 == 1 {
return *k.0;
}
}
0
}
pub fn bit_manipulation_sol(nums: Vec<i32>) -> i32 {
let mut x1 = 0;
let mut x2 = 0;
let mut mask = 0;
for num in nums {
x2 ^= x1 & num;
x1 ^= num;
mask = !(x1 & x2);
x2 &= mask;
x1 &= mask;
}
x1
}
}
// @lc code=end