Re: [閒聊] 每日LeetCode

作者: yam276 ('_')   2024-01-17 11:45:40
https://leetcode.com/problems/unique-number-of-occurrences/
1207. Unique Number of Occurrences
給一個陣列,判斷每種數字的出現次數是否為唯一
思路:
1. 先用HashMap蒐集出現次數
2. 嘗試用出現次數插入一個HashSet,失敗代表非唯一
Code:
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn unique_occurrences(arr: Vec<i32>) -> bool {
let mut hash_arr: HashMap<i32, i32> = HashMap::new();
for num in arr{
*hash_arr.entry(num).or_insert(0) += 1;
}
let mut occurrences = HashSet::new();
for count in hash_arr.values() {
if !occurrences.insert(count) {
return false;
}
}
true
}
}
作者: ILoveErr (英梨梨我老婆)   2024-01-17 11:46:00
大師
作者: SecondRun (雨夜琴聲)   2024-01-17 11:48:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com