Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Random;
- /**
- * Using a ArrayList and HashMap
- *
- * Time Complexity: All function have average O(1)
- *
- * Space Complexity: O(N)
- *
- * N = Number of values currently stored in the data structure.
- */
- class RandomizedCollection {
- ArrayList<Integer> nums;
- HashMap<Integer, HashSet<Integer>> map;
- Random rand;
- /** Initialize your data structure here. */
- public RandomizedCollection() {
- nums = new ArrayList<>();
- map = new HashMap<>();
- rand = new Random();
- }
- /**
- * Inserts a value to the collection. Returns true if the collection did not
- * already contain the specified element.
- */
- public boolean insert(int val) {
- boolean flag = false;
- if (!map.containsKey(val)) {
- flag = true;
- map.put(val, new HashSet<>());
- }
- nums.add(val);
- map.get(val).add(nums.size() - 1);
- return flag;
- }
- /**
- * Removes a value from the collection. Returns true if the collection contained
- * the specified element.
- */
- public boolean remove(int val) {
- if (!map.containsKey(val)) {
- return false;
- }
- HashSet<Integer> indexes = map.get(val);
- int index = indexes.iterator().next();
- indexes.remove(index);
- if (indexes.size() == 0) {
- map.remove(val);
- }
- if (index != nums.size() - 1) {
- int lastVal = nums.get(nums.size() - 1);
- nums.set(index, lastVal);
- HashSet<Integer> lastValIndexes = map.get(lastVal);
- lastValIndexes.remove(nums.size() - 1);
- lastValIndexes.add(index);
- }
- nums.remove(nums.size() - 1);
- return true;
- }
- /** Get a random element from the collection. */
- public int getRandom() {
- return nums.get(rand.nextInt(nums.size()));
- }
- }
- /**
- * Your RandomizedCollection object will be instantiated and called as such:
- * RandomizedCollection obj = new RandomizedCollection(); boolean param_1 =
- * obj.insert(val); boolean param_2 = obj.remove(val); int param_3 =
- * obj.getRandom();
- */
Add Comment
Please, Sign In to add comment