zoukankan      html  css  js  c++  java
  • 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 }
    
    
    


  • 相关阅读:
    20160813上午训练记录
    [bzoj 2159]Crash的文明世界
    【娱乐】高端小游戏Manufactoria
    【教程】如何正确的写一个Lemon/Cena的SPJ(special judge)
    [CF]codeforces round#366(div2)滚粗记
    洛谷 [P3265] 装备购买
    POJ 1830 开关问题
    洛谷 [P4035] 球形空间生成器
    BZOJ 2973 入门OJ4798 石头游戏
    洛谷 [P1939] 矩阵加速数列
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7677994.html
Copyright © 2011-2022 走看看