作者:
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
}
}