-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added intersection of two arrays solution.
- Loading branch information
Showing
3 changed files
with
37 additions
and
0 deletions.
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 |
---|---|---|
@@ -0,0 +1,35 @@ | ||
use std::collections::HashMap; | ||
|
||
pub fn intersect(numbers_one: Vec<i32>, numbers_two: Vec<i32>) -> Vec<i32> { | ||
let mut counts = numbers_one | ||
.into_iter() | ||
.fold(HashMap::new(), |mut acc, curr| { | ||
*acc.entry(curr).or_insert(0) += 1; | ||
acc | ||
}); | ||
|
||
let mut result = Vec::new(); | ||
for number in numbers_two { | ||
if let Some(count) = counts.get_mut(&number) { | ||
if *count > 0 { | ||
result.push(number); | ||
*count -= 1; | ||
} | ||
} | ||
} | ||
result | ||
} | ||
g | ||
#[cfg(test)] | ||
mod tests { | ||
use std::vec; | ||
|
||
use super::intersect; | ||
|
||
#[test] | ||
fn test_intersect() { | ||
let result = intersect(vec![1, 2, 3, 3, 1, 5, 6], vec![1, 3, 3, 1]); | ||
let expected = vec![1, 3, 3, 1]; | ||
assert_eq!(expected, result) | ||
} | ||
} |
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 |
---|---|---|
|
@@ -42,3 +42,4 @@ mod unique_occurrences; | |
mod zero_or_one; | ||
mod sort_colors; | ||
mod rotate_digits; | ||
mod intersection_two; |