Skip to content

Commit

Permalink
Merge pull request #3259 from saurabh10041998/insert-delete-get-random
Browse files Browse the repository at this point in the history
Create: 0380-insert-delete-getrandom.rs
  • Loading branch information
Ykhan799 authored Nov 10, 2024
2 parents bec4e98 + d482ed5 commit d68871c
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions rust/0380-insert-delete-getrandom-o1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use rand::seq::SliceRandom;
use std::collections::HashMap;

pub struct RandomizedSet {
mp: HashMap<i32, i32>,
arr: Vec<i32>,
}

impl RandomizedSet {
fn new() -> Self {
RandomizedSet {
mp: HashMap::new(),
arr: Vec::new(),
}
}

fn insert(&mut self, val: i32) -> bool {
let res = !self.mp.contains_key(&val);
if res {
self.mp.insert(val, self.arr.len() as i32);
self.arr.push(val);
}
res
}
fn remove(&mut self, val: i32) -> bool {
let res = self.mp.contains_key(&val);
if res {
let idx = *self.mp.get(&val).unwrap();
self.mp
.entry(*self.arr.last().unwrap())
.and_modify(|v| *v = idx);
self.arr.swap_remove(idx as usize);
self.mp.remove(&val);
}
res
}
fn get_random(&self) -> i32 {
*self.arr.choose(&mut rand::thread_rng()).unwrap()
}
}

0 comments on commit d68871c

Please sign in to comment.