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.

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 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

此题解决了我很久以前的疑问,原来map的containsKey操作的时间复杂度是常数时间完成的,代码实现起来不是很难,做Arraylist的目的是获取random的时候用,hashmap的value值用来
设置list的索引值,代码如下:
 1 public class RandomizedSet {
 2     ArrayList<Integer> nums;
 3     Map<Integer,Integer> map;
 4     java.util.Random rand = new java.util.Random();
 5     /** Initialize your data structure here. */
 6     public RandomizedSet() {
 7         nums = new ArrayList<Integer>();
 8         map = new HashMap<Integer,Integer>();
 9     }
10     
11     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
12     public boolean insert(int val) {
13         if(map.containsKey(val)){
14             return false;
15         }else{
16             map.put(val,nums.size());
17             nums.add(val);
18         }
19         return true;
20     }
21     
22     /** Removes a value from the set. Returns true if the set contained the specified element. */
23     public boolean remove(int val) {
24         if(!map.containsKey(val)){
25             return false;
26         }else{
27             if(map.get(val)<nums.size()-1){
28                 int loc = map.get(val);
29                 int value = nums.get(nums.size()-1);
30                 nums.set(loc,value);
31                 map.put(value,loc);
32             }
33             map.remove(val);
34             nums.remove(nums.size()-1);
35             return true;
36         }
37     }
38     
39     /** Get a random element from the set. */
40     public int getRandom() {
41         return nums.get(rand.nextInt(nums.size()));
42     }
43 }
44 
45 /**
46  * Your RandomizedSet object will be instantiated and called as such:
47  * RandomizedSet obj = new RandomizedSet();
48  * boolean param_1 = obj.insert(val);
49  * boolean param_2 = obj.remove(val);
50  * int param_3 = obj.getRandom();
51  */
原文地址:https://www.cnblogs.com/codeskiller/p/6508486.html