use std::collections::HashMap; | |||||
// I'm fairly sure there's a better more mathsy way of doing this but I can't work it out yet. | |||||
pub fn single_number(nums: Vec<i32>) -> i32 { | |||||
let mut hm = HashMap::<i32, i32>::new(); | |||||
for n in nums { | |||||
if hm.contains_key(&n) { | |||||
hm.remove(&n); | |||||
} else { | |||||
hm.insert(n, 0); | |||||
} | |||||
} | |||||
match hm.keys().next() { | |||||
Some(i) => *i, | |||||
_ => 0 | |||||
} | |||||
} | |||||
pub fn main() { | |||||
println!("Expected: 1"); | |||||
println!("Got: {}", single_number(vec![1, 2, 3, 4, 3, 4, 2])); | |||||
} |
Given a non-empty array of integers, every element appears twice except for one. Find that single one. | |||||
Note: | |||||
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? | |||||
Example 1: | |||||
Input: [2,2,1] | |||||
Output: 1 | |||||
Example 2: | |||||
Input: [4,1,2,1,2] | |||||
Output: 4 |
#!/bin/bash | |||||
rustc main.rs | |||||
./main | |||||
rm main |