Re: [闲聊] 每日leetcode

楼主: yam276 ('_')   2024-06-07 06:42:37
※ 引述《JIWP (神楽めあ的钱包)》之铭言:
: 846. Hand of Straights
: 有一组整数array hand和一个整数groupsize
: 请问hand里的元素是否能分成数个groups
: 其中每个group大小为groupsize
: 且group中的每个数字是连续的
: 思路:
一样使用一个计算frqency的哈希表来实作
Code:
use std::collections::HashMap;
impl Solution {
pub fn is_n_straight_hand(mut hand: Vec<i32>, group_size: i32) -> bool {
hand.sort_unstable();
let mut card_freq = HashMap::new();
for &card in hand.iter() {
*card_freq.entry(card).or_insert(0) += 1;
}
for &card in &hand {
if *card_freq.get(&card).unwrap_or(&0) > 0 {
for i in 0..group_size {
let freq = card_freq.entry(card + i).or_insert(0);
if *freq > 0 {
*freq -= 1;
}
else {
return false;
}
}
}
}
true
}
}
作者: sustainer123 (caster)   2024-06-07 07:50:00
大师
作者: wwndbk (黑人问号)   2024-06-07 08:16:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com