• 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 }
    
    
    


  • 相关阅读:
    Task级别任务调度分析---源码级
    解决部署K8S集群时flannel无法下载问题
    安装kubernetes+docker集群,一篇文章搞定
    充值-实体类+查询
    充值-controller
    多对一的增删改查-list页面,add页面,update页面,tongji页面
    多对一的增删改查-dao层
    多对一的增删改查-sql语句
    多对一的增删改查-controller
    多对一的增删改查-service和impl
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7677994.html
Copyright © 2020-2023  润新知