|
| 1 | +package code; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +/* |
| 8 | + * 380. Insert Delete GetRandom O(1) |
| 9 | + * 题意:设计一个数据结构,插入,删除,随机获得一个元素 这三个操作的复杂度都为O(1) |
| 10 | + * 难度:Medium |
| 11 | + * 分类:Array, Hash Table, Design |
| 12 | + * 思路:List 的插入和删除都是O(1), 通过hashmap绑定来使得Get也为O(1) |
| 13 | + * Tips: |
| 14 | + */ |
| 15 | +public class lc380 { |
| 16 | + public class RandomizedSet { |
| 17 | + |
| 18 | + HashMap<Integer, Integer> valToInd; |
| 19 | + List<Integer> list; |
| 20 | + int ind = 0; |
| 21 | + |
| 22 | + /** Initialize your data structure here. */ |
| 23 | + public RandomizedSet() { |
| 24 | + valToInd = new HashMap<>(); |
| 25 | + list = new ArrayList<>(); |
| 26 | + } |
| 27 | + |
| 28 | + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ |
| 29 | + public boolean insert(int val) { |
| 30 | + if(valToInd.containsKey(val)) return false; |
| 31 | + list.add(val); |
| 32 | + valToInd.put(val,list.size()-1); |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + /** Removes a value from the set. Returns true if the set contained the specified element. */ |
| 37 | + public boolean remove(int val) { |
| 38 | + int ind = valToInd.getOrDefault(val,-1); |
| 39 | + if(ind == -1) return false; |
| 40 | + Collections.swap(list,ind,list.size()-1); |
| 41 | + int swappedWith = list.get(ind); |
| 42 | + valToInd.put(swappedWith,ind); |
| 43 | + list.remove(list.size()-1); |
| 44 | + valToInd.remove(val); |
| 45 | + return true; |
| 46 | + } |
| 47 | + |
| 48 | + /** Get a random element from the set. */ |
| 49 | + public int getRandom() { |
| 50 | + int max = list.size(); |
| 51 | + int min = 0; |
| 52 | + int ind = (int)(Math.random() * (max - min) + min); |
| 53 | + return list.get(ind); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments