1988coder

381. Insert Delete GetRandom O(1) - Duplicates allowed

Jan 22nd, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.HashSet;
  4. import java.util.Random;
  5.  
  6. /**
  7.  * Using a ArrayList and HashMap
  8.  *
  9.  * Time Complexity: All function have average O(1)
  10.  *
  11.  * Space Complexity: O(N)
  12.  *
  13.  * N = Number of values currently stored in the data structure.
  14.  */
  15. class RandomizedCollection {
  16.  
  17.     ArrayList<Integer> nums;
  18.     HashMap<Integer, HashSet<Integer>> map;
  19.     Random rand;
  20.  
  21.     /** Initialize your data structure here. */
  22.     public RandomizedCollection() {
  23.         nums = new ArrayList<>();
  24.         map = new HashMap<>();
  25.         rand = new Random();
  26.     }
  27.  
  28.     /**
  29.      * Inserts a value to the collection. Returns true if the collection did not
  30.      * already contain the specified element.
  31.      */
  32.     public boolean insert(int val) {
  33.         boolean flag = false;
  34.         if (!map.containsKey(val)) {
  35.             flag = true;
  36.             map.put(val, new HashSet<>());
  37.         }
  38.         nums.add(val);
  39.         map.get(val).add(nums.size() - 1);
  40.         return flag;
  41.     }
  42.  
  43.     /**
  44.      * Removes a value from the collection. Returns true if the collection contained
  45.      * the specified element.
  46.      */
  47.     public boolean remove(int val) {
  48.         if (!map.containsKey(val)) {
  49.             return false;
  50.         }
  51.  
  52.         HashSet<Integer> indexes = map.get(val);
  53.         int index = indexes.iterator().next();
  54.         indexes.remove(index);
  55.         if (indexes.size() == 0) {
  56.             map.remove(val);
  57.         }
  58.  
  59.         if (index != nums.size() - 1) {
  60.             int lastVal = nums.get(nums.size() - 1);
  61.             nums.set(index, lastVal);
  62.             HashSet<Integer> lastValIndexes = map.get(lastVal);
  63.             lastValIndexes.remove(nums.size() - 1);
  64.             lastValIndexes.add(index);
  65.         }
  66.         nums.remove(nums.size() - 1);
  67.  
  68.         return true;
  69.     }
  70.  
  71.     /** Get a random element from the collection. */
  72.     public int getRandom() {
  73.         return nums.get(rand.nextInt(nums.size()));
  74.     }
  75. }
  76.  
  77. /**
  78.  * Your RandomizedCollection object will be instantiated and called as such:
  79.  * RandomizedCollection obj = new RandomizedCollection(); boolean param_1 =
  80.  * obj.insert(val); boolean param_2 = obj.remove(val); int param_3 =
  81.  * obj.getRandom();
  82.  */
Add Comment
Please, Sign In to add comment