Skip to content

Commit

Permalink
Added intersection of two arrays solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Jul 2, 2024
1 parent a108efa commit 9b115e7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ other languages.
- Sort by Number of Bits (https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits)
- Make the String Great (https://leetcode.com/problems/make-the-string-great/)
- Excel Column Number (https://leetcode.com/problems/excel-sheet-column-number/)
- Intersection of Two Arrays (https://leetcode.com/problems/intersection-of-two-arrays-ii)

#### Medium

Expand Down
35 changes: 35 additions & 0 deletions src/leetcode/intersection_two.rs
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)
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ mod unique_occurrences;
mod zero_or_one;
mod sort_colors;
mod rotate_digits;
mod intersection_two;

0 comments on commit 9b115e7

Please sign in to comment.