380. Insert Delete GetRandom O(1)
map记录位置
remove时候把最后一位跟要remove的交换 然后去掉最后一位 这样可以达到O(1)
1 class RandomizedSet { 2 HashMap<Integer, Integer> map; 3 List<Integer> list; 4 Random random = new Random(); 5 6 /** Initialize your data structure here. */ 7 public RandomizedSet() { 8 map = new HashMap<>(); 9 list = new ArrayList<>(); 10 } 11 12 /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ 13 public boolean insert(int val) { 14 if(map.containsKey(val)){ 15 return false; 16 }else{ 17 map.put(val, map.size()); 18 list.add(val); 19 return true; 20 } 21 22 } 23 24 /** Removes a value from the set. Returns true if the set contained the specified element. */ 25 public boolean remove(int val) { 26 if(map.containsKey(val)){ 27 int index = map.get(val); 28 int last = list.get(list.size()-1); 29 list.set(index, last); 30 map.put(last, index); 31 map.remove(val); 32 list.remove(list.size()-1); 33 return true; 34 } 35 return false; 36 } 37 38 /** Get a random element from the set. */ 39 public int getRandom() { 40 int index = random.nextInt(list.size()); 41 return list.get(index); 42 } 43 }