-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
30 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -115,3 +115,4 @@ mod make_increasing; | |
mod rotate_box; | ||
mod find_champion; | ||
mod single_number; | ||
mod single_number_ii; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
use std::collections::HashMap; | ||
|
||
pub fn single_number(numbers: Vec<i32>) -> i32 { | ||
let counter = numbers.into_iter().fold(HashMap::new(), |mut acc, curr| { | ||
*acc.entry(curr).or_insert(0) += 1; | ||
acc | ||
}); | ||
counter.into_iter().find(|(_, v)| *v == 1).unwrap().0 | ||
} | ||
|
||
// Optimized solution | ||
// Credit: https://leetcode.com/problems/single-number-ii/solutions/2389678/rust-concise-solution-with-ternary-logic-explained/ | ||
// pub fn single_number(numbers: Vec<i32>) -> i32 { | ||
// numbers | ||
// .into_iter() | ||
// .fold([0, 0], |[a, b], x| [a ^ x & !b, a & x | b & !x])[0] | ||
// } | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn finds_the_number_that_appears_once() { | ||
assert_eq!(3, single_number(vec![2, 2, 3, 2])); | ||
} | ||
} |