Re: [闲聊] 每日leetcode

楼主: yam276 ('_')   2024-07-02 17:37:39
※ 引述《smart0eddie (smart0eddie)》之铭言:
: 20240702
: 350. Intersection of Two Arrays II
: Given two integer arrays nums1 and nums2, return an array of their
: intersection. Each element in the result must appear as many times as it
: shows in both arrays and you may return the result in any order.
HashMap
Code:
use std::collections::HashMap;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut nums1_hash = HashMap::new();
let mut nums2_hash = HashMap::new();
for &num in &nums1 {
*nums1_hash.entry(num).or_insert(0) += 1;
}
for &num in &nums2 {
*nums2_hash.entry(num).or_insert(0) += 1;
}
let mut result = Vec::new();
for (&num, &count) in &nums1_hash {
if let Some(&count2) = nums2_hash.get(&num) {
let min_count = count.min(count2);
for _ in 0..min_count {
result.push(num);
}
}
}
result
}
}
作者: Smallsh (Smallsh)   2024-07-02 17:38:00
大师
作者: sustainer123 (caster)   2024-07-02 17:41:00
大师
作者: DJYOMIYAHINA (通通打死)   2024-07-02 17:41:00
大湿

Links booklink

Contact Us: admin [ a t ] ucptt.com