作者yam276 (虛構史學家)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Tue Jul 2 17:37:39 2024
※ 引述《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
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.48.170 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1719913061.A.A30.html
推 Smallsh: 大師 07/02 17:38
推 sustainer123: 大師 07/02 17:41
推 DJYOMIYAHINA: 大濕 07/02 17:41