380. Insert Delete GetRandom O(1)

Design a data structure that supports all following operations in average O(1) time.

 

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

设计一个数据结构,使得插入、删除,随机获取一个元素的时间复杂度都是O(1) 

 
复制代码
 1 class RandomizedSet {
 2 
 3     ArrayList<Integer> nums; //存放具体的值
 4     HashMap<Integer, Integer> locs; //标记每个值在nums中的位置
 5     java.util.Random rand = new java.util.Random();
 6     /** Initialize your data structure here. */
 7     public RandomizedSet() {
 8         nums = new ArrayList<Integer>();
 9         locs = new HashMap<Integer, Integer>();
10     }
11     
12     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
13     public boolean insert(int val) {
14         boolean contain = locs.containsKey(val);
15         if ( contain ) return false;
16         locs.put( val, nums.size());
17         nums.add(val);
18         return true;
19     }
20     
21     /** Removes a value from the set. Returns true if the set contained the specified element. */
22     public boolean remove(int val) {
23         boolean contain = locs.containsKey(val);
24         if ( ! contain ) return false;
25         int loc = locs.get(val);
26         if (loc < nums.size() - 1 ) { // not the last one than swap the last one with this val
27             int lastone = nums.get(nums.size() - 1 );
28             nums.set( loc , lastone );//将最后一个位置的元素拷贝到本位置,达到覆盖被删除元素的目的
29             locs.put(lastone, loc); //因为map中最后一个位置的元素被移走了,所以要同步修改mamp中的位置索引
30         }
31         locs.remove(val); //删除map中要被删除元素
32         nums.remove(nums.size() - 1);//删除list中最后一个元素
33         return true;
34     }
35     
36     /** Get a random element from the set. */
37     public int getRandom() {
38         return nums.get( rand.nextInt(nums.size()) );
39     }
40 }
复制代码

 



posted @   daniel456  阅读(138)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示