1. 程式人生 > >LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入刪除和獲得隨機數 常數時間 允許重復項)

LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入刪除和獲得隨機數 常數時間 允許重復項)

anti mean 插入 another right operation view 回顧 true

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

Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();


題目標簽:Array, Hash Table, Design   這道題目基於#380 的情況下,可以允許有重復項。回顧一下380, 因為要達到 insert, remove 和 getRandom 都是O(1) 的時間,我們需要ArrayList 來保存所有的數字,利用map 來保存 數字 和 index 之間的映射。   這道題目允許了重復項,那麽在map 裏 key 是數字, value 是index, 這裏的index 就會不止一個了。我們要把所有重復的數字的 index 也保存進來, 所以把 map 裏value 改成 HashSet 來保存所有的index。   insert val:如果map裏沒有val,需要新建一個HashSet,並且加入nums (ArrayList);        如果有val,直接加入新的index 進HashSet,並且加入nums (ArrayList);            remove val:如果val 在nums 裏是最後一個的話,只需要在map 裏刪除val 的index, 並且在nums 裏刪除最後一個數字。         如果val 在nums 裏不是最後一個的話,需要額外的把 nums 裏最後一個數字的值 復制到 val, 刪除val 在map裏的 index,還要把最後一個數字的index 在map 裏更新,並且在nums 裏刪除最後一個數字。   其他基本都和#380 差不多,具體看code。

Java Solution:

Runtime beats 88.45%

完成日期:09/18/2017

關鍵詞:Array, Hash Table, Design

關鍵點:利用array 保存數值;利用map<Integer, HashSet<>>保存 - 數值 當作key,數值在array裏的所有index 保存在HashSet,當作value。

 1 class RandomizedCollection 
 2 {
 3     private HashMap<Integer, HashSet<Integer>> map; // key is value, value is index HashSet
 4     private ArrayList<Integer> nums; // store all vals
 5     private java.util.Random rand = new java.util.Random();
 6     
 7     /** Initialize your data structure here. */
 8     public RandomizedCollection() 
 9     {
10         map = new HashMap<>();
11         nums = new ArrayList<>();
12     }
13     
14     /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
15     public boolean insert(int val) 
16     {
17         boolean contain = map.containsKey(val);
18         
19         // if map doesn‘t have val, meaning map doesn‘t have HashSet
20         if(!contain) 
21             map.put(val, new HashSet<Integer>()); // create HashSet
22         
23         // add index into HashSet
24         map.get(val).add(nums.size());
25         nums.add(val);
26         
27         return !contain; // if collection has val, return false; else return true
28     }
29     
30     /** Removes a value from the collection. Returns true if the collection contained the specified element. */
31     public boolean remove(int val) 
32     {
33         boolean contain = map.containsKey(val);
34         if(!contain) 
35             return false;
36         // get an index from HashSet of Map
37         int valIndex = map.get(val).iterator().next();
38         map.get(val).remove(valIndex); // remove this index from val‘s set
39         
40         if(valIndex != nums.size() - 1) // if this val is not the last one in nums
41         {
42             // copy the last one value into this val‘s position
43             int lastNum = nums.get(nums.size() - 1);
44             nums.set(valIndex, lastNum);
45             // update the lastNum index in HashSet
46             map.get(lastNum).remove(nums.size() - 1); // remove the last number‘s index from set
47             map.get(lastNum).add(valIndex); // add new index into set
48         }
49         
50         if(map.get(val).isEmpty()) // if val‘s set is empty
51             map.remove(val); // remove val from map
52         
53         nums.remove(nums.size() - 1); // only remove last one O(1)
54           
55         return true;
56     }
57     
58     /** Get a random element from the collection. */
59     public int getRandom() 
60     {
61         return nums.get(rand.nextInt(nums.size()));
62     }
63 }
64 
65 /**
66  * Your RandomizedCollection object will be instantiated and called as such:
67  * RandomizedCollection obj = new RandomizedCollection();
68  * boolean param_1 = obj.insert(val);
69  * boolean param_2 = obj.remove(val);
70  * int param_3 = obj.getRandom();
71  */

參考資料:

https://discuss.leetcode.com/topic/53216/java-solution-using-a-hashmap-and-an-arraylist-along-with-a-follow-up-131-ms/5

LeetCode 題目列表 - LeetCode Questions List

LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入刪除和獲得隨機數 常數時間 允許重復項)