20240321 Finished

This commit is contained in:
jackfiled 2024-03-21 11:04:22 +08:00
parent 8c9a92ff9a
commit 547630c8ce
2 changed files with 106 additions and 1 deletions

View File

@ -79,4 +79,5 @@ mod p2684_maximum_number_of_moves_in_a_grid;
mod p310_minimum_height_trees;
mod p303_range_sum_query_immutable;
mod p1793_maximum_score_of_a_good_subarray;
mod p1969_minimum_non_zero_product_of_the_array_elements;
mod p1969_minimum_non_zero_product_of_the_array_elements;
mod p2671_frequency_tracker;

View File

@ -0,0 +1,104 @@
/**
* [2671] Frequency Tracker
*/
pub struct Solution {}
// submission codes start here
use std::collections::{HashMap, HashSet};
struct FrequencyTracker {
number_map : HashMap<i32, i32>,
frequency_map : HashMap<i32, HashSet<i32>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl FrequencyTracker {
fn new() -> Self {
FrequencyTracker {
number_map: HashMap::new(),
frequency_map: HashMap::new(),
}
}
fn add(&mut self, number: i32) {
let mut entry = self.number_map.entry(number).or_insert(0);
if *entry != 0 {
if let Some(set) = self.frequency_map.get_mut(&entry) {
set.remove(&number);
}
}
*entry += 1;
let set = self.frequency_map.entry(*entry)
.or_insert(HashSet::new());
set.insert(number);
}
fn delete_one(&mut self, number: i32) {
if let Some(entry) = self.number_map.get_mut(&number) {
if *entry == 0 {
return;
}
if let Some(set) = self.frequency_map.get_mut(&entry) {
set.remove(&number);
}
*entry -= 1;
let set = self.frequency_map.entry(*entry)
.or_insert(HashSet::new());
set.insert(number);
}
}
fn has_frequency(&self, frequency: i32) -> bool {
let set = self.frequency_map.get(&frequency);
match set {
Some(set) => set.len() != 0,
None => false
}
}
}
/**
* Your FrequencyTracker object will be instantiated and called as such:
* let obj = FrequencyTracker::new();
* obj.add(number);
* obj.delete_one(number);
* let ret_3: bool = obj.has_frequency(frequency);
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2671() {
let mut tracker = FrequencyTracker::new();
tracker.add(10);
tracker.delete_one(5);
assert!(tracker.has_frequency(1));
tracker.delete_one(10);
tracker.delete_one(9);
tracker.delete_one(10);
assert!(!tracker.has_frequency(1));
tracker.add(4);
assert!(tracker.has_frequency(1));
tracker.delete_one(4);
assert!(!tracker.has_frequency(1));
assert!(!tracker.has_frequency(1));
tracker.add(10);
assert!(tracker.has_frequency(1));
}
}