Advertisement
1988coder

380. Insert Delete GetRandom O(1)

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