[闲聊] 每日leetcode 75 - Day7 - 4

楼主: yam276 ('_')   2025-06-09 16:18:50
1679. Max Number of K-Sum Pairs
题目:
给你一堆牌抽鬼牌
抽到合计 k 的可以拔掉
看能凑几对
思路:
用双指标要先排序变成O(n log n) 很痛苦
所以用 HashMap
而且我本来 for 扫两遍
但后来发现这一题可以边做边蒐集
不是需要先蒐集满的题目
可以只用一个 for 解完
:O
Code:
use std::collections::{hash_map::Entry, HashMap};
impl Solution {
pub fn max_operations(nums: Vec<i32>, k: i32) -> i32 {
let mut counts = HashMap::new();
let mut count = 0;
for num in nums {
match counts.entry(k - num) {
Entry::Occupied(mut e) => {
*e.get_mut() -= 1;
if *e.get_mut() == 0 {
e.remove_entry();
}
count += 1;
}
Entry::Vacant(_) => {
*counts.entry(num).or_insert(0) += 1;
}
}
}
count
}
}

Links booklink

Contact Us: admin [ a t ] ucptt.com