zoukankan      html  css  js  c++  java
  • LeetCode-Insert Delete GetRandom O(1)

    Design a data structure that supports all following operations in 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.

    Example:

    // Init an empty set.
    RandomizedSet randomSet = new RandomizedSet();
    
    // Inserts 1 to the set. Returns true as 1 was inserted successfully.
    randomSet.insert(1);
    
    // Returns false as 2 does not exist in the set.
    randomSet.remove(2);
    
    // Inserts 2 to the set, returns true. Set now contains [1,2].
    randomSet.insert(2);
    
    // getRandom should return either 1 or 2 randomly.
    randomSet.getRandom();
    
    // Removes 1 from the set, returns true. Set now contains [2].
    randomSet.remove(1);
    
    // 2 was already in the set, so return false.
    randomSet.insert(2);
    
    // Since 1 is the only number in the set, getRandom always return 1.
    randomSet.getRandom();
    
    Analysis:
    For O(1) insert and remove, we need HashMap. For O(1) random access, we need to arrange all elements in an array. To perform insert and remove for an array in O(1), we can swap the deleted element with the last element and decrease the list end.
     
     Solution:
     1 import java.util.Random;
     2 
     3 public class RandomizedSet {
     4     HashMap<Integer,Integer> map;
     5     List<Integer> list;
     6     int listEnd;
     7 
     8     /** Initialize your data structure here. */
     9     public RandomizedSet() {
    10         map = new HashMap<Integer,Integer>();
    11         list = new ArrayList<Integer>();
    12         listEnd = 0;
    13     }
    14     
    15     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    16     public boolean insert(int val) {
    17         if (map.containsKey(val)) return false;
    18         
    19         map.put(val,listEnd);
    20         if (listEnd == list.size()){
    21             list.add(val);
    22         } else {
    23             list.set(listEnd,val);
    24         }
    25         listEnd++;
    26         return true;
    27     }
    28     
    29     /** Removes a value from the set. Returns true if the set contained the specified element. */
    30     public boolean remove(int val) {
    31         if (map.isEmpty() || !map.containsKey(val)) return false;
    32         
    33         // To remove an element, we swap it with the last element and decrease the index. 
    34         int index = map.get(val);
    35         int lastVal = list.get(--listEnd);
    36         list.set(index,lastVal);
    37         map.put(lastVal,index); // remeber to update the last element's index in HashMap. 
    38         
    39         // NOTE: this must be performed after swap, because if the removed element is the last element, perform the following earlier will leave the HashMap, which may block inserting the same element later and create a async between HashMap and List.
    40         map.remove(val);
    41         return true;
    42     }
    43     
    44     /** Get a random element from the set. */
    45     public int getRandom() {
    46         Random engine = new Random();
    47         int index = engine.nextInt(listEnd);
    48         return list.get(index);
    49     }
    50 }
    51 
    52 /**
    53  * Your RandomizedSet object will be instantiated and called as such:
    54  * RandomizedSet obj = new RandomizedSet();
    55  * boolean param_1 = obj.insert(val);
    56  * boolean param_2 = obj.remove(val);
    57  * int param_3 = obj.getRandom();
    58  */
  • 相关阅读:
    管理之道
    Swagger-editor安装启动及错误处理,注意事项
    装箱 拆箱 枚举 注解 多态
    Spring Security 内置过滤器表
    Spring Boot入门 and Spring Boot与ActiveMQ整合
    消息中间件解决方案JMS
    网页静态化解决方案-Freemarker demo+语法
    spring-data-radis错误
    java基础总结
    swift oc 混编的头文件
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5736497.html
Copyright © 2011-2022 走看看