堅持天天一道題,刷題學習Rust.git
https://leetcode-cn.com/problems/insert-delete-getrandom-o1/
設計一個支持在平均 時間複雜度 O(1) 下,執行如下操做的數據結構。github
insert(val):當元素 val 不存在時,向集合中插入該項。
remove(val):元素 val 存在時,從集合中移除該項。
getRandom:隨機返回現有集合中的一項。每一個元素應該有相同的機率被返回。
示例 :數組
// 初始化一個空的集合。
RandomizedSet randomSet = new RandomizedSet();數據結構
// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);dom
// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);學習
// 向集合中插入 2 。返回 true 。集合如今包含 [1,2] 。
randomSet.insert(2);設計
// getRandom 應隨機返回 1 或 2 。
randomSet.getRandom();code
// 從集合中移除 1 ,返回 true 。集合如今包含 [2] 。
randomSet.remove(1);ci
// 2 已在集合中,因此返回 false 。
randomSet.insert(2);element
// 因爲 2 是集合中惟一的數字,getRandom 老是返回 2 。
randomSet.getRandom();
思路:1.用slice存值,用map保存值在slice中的index;
2.每次刪除時,爲了不移動元素,用數組末尾元素覆蓋須要刪除的元素,而後刪除數組末尾元素;
extern crate rand; use rand::Rng; use std::collections::HashMap; use std::collections::HashSet; struct RandomizedSet { m: HashMap<i32, usize>, v: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl RandomizedSet { /** Initialize your data structure here. */ fn new() -> Self { RandomizedSet { m: HashMap::new(), v: Vec::new(), } } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ pub fn insert(&mut self, val: i32) -> bool { if self.m.contains_key(&val) { return false; } let i = self.m.len(); if self.v.len() > i { //通過刪除之後v裏面空間可能很是富裕,直接用現有的纔對 self.v[i] = val; } else { self.v.push(val); } self.m.insert(val, i); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ pub fn remove(&mut self, val: i32) -> bool { if !self.m.contains_key(&val) { return false; } let i = *self.m.get(&val).expect("must ok"); if i != self.m.len() - 1 { //若是是最後一個,就不用調整了 self.v[i] = self.v[self.m.len() - 1]; //最後一個值填充到i self.m.insert(self.v[i], i); } self.m.remove(&val); return true; } /** Get a random element from the set. */ pub fn get_random(&self) -> i32 { let mut rng = rand::thread_rng(); let mut i: usize = rng.gen(); i = i % self.m.len(); return self.v[i]; } }
rust標準庫中竟然沒有隨機數生成器.
歡迎關注個人github,本項目文章全部代碼均可以找到.