20241024 finished.

This commit is contained in:
2024-10-24 09:08:13 +08:00
parent 3102da99a8
commit bce8de1c85
266 changed files with 2321 additions and 2014 deletions

View File

@@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
use rand::{rngs::ThreadRng, Rng};
use std::collections::HashMap;
@@ -12,25 +11,23 @@ struct RandomizedSet {
array: Vec<i32>,
pos_table: HashMap<i32, usize>,
pos_now: usize,
rng: ThreadRng
rng: ThreadRng,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl RandomizedSet {
fn new() -> Self {
RandomizedSet {
array: vec![0;200_001],
array: vec![0; 200_001],
pos_table: HashMap::new(),
pos_now: 0,
rng: rand::thread_rng()
rng: rand::thread_rng(),
}
}
fn insert(&mut self, val: i32) -> bool {
if self.pos_table.contains_key(&val) {
return false;
@@ -41,22 +38,22 @@ impl RandomizedSet {
self.pos_now += 1;
true
}
fn remove(&mut self, val: i32) -> bool {
return match self.pos_table.get(&val) {
Some(&pos) => {
let last = self.array[self.pos_now - 1];
self.pos_table.insert(last, pos);
self.array[pos] = last;
self.pos_now -= 1;
self.pos_now -= 1;
self.pos_table.remove(&val);
true
},
None => false
}
}
None => false,
};
}
fn get_random(&mut self) -> i32 {
let pos = self.rng.gen_range(0..self.pos_now);
self.array[pos]