本题有点类似设计题
    原本想到了大体思路:

    • HashMap<Integer, Integer>: key是存的val,value是ArrayList<Integer>的index
    • ArrayList<Integer>: 存的是val

    但是一开始没有想明白如果remove元素的话,那么HashMap<Integer, Integer>里存的index就都变了,在被删除的元素的后面的index都会自动往前移动1
    看了答案后想明白了,可以在删除前,手动把要删除的元素移动到ArrayList<Integer>的末尾,这样就可以避免这个问题。

    • 时间复杂度:
      • insert(): 380. Insert Delete GetRandom O(1) - 图1
      • remove(): 380. Insert Delete GetRandom O(1) - 图2
      • getRandom(): 380. Insert Delete GetRandom O(1) - 图3
    • 空间复杂度:380. Insert Delete GetRandom O(1) - 图4

    代码如下:

    1. class RandomizedSet {
    2. private Map<Integer, Integer> mySet;
    3. private List<Integer> myList;
    4. private Random rand;
    5. /** Initialize your data structure here. */
    6. public RandomizedSet() {
    7. mySet = new HashMap<>();
    8. myList = new ArrayList<>();
    9. rand = new Random();
    10. }
    11. /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    12. public boolean insert(int val) {
    13. if (mySet.containsKey(val)) {
    14. return false;
    15. }
    16. myList.add(val);
    17. mySet.put(val, myList.size() - 1);
    18. return true;
    19. }
    20. /** Removes a value from the set. Returns true if the set contained the specified element. */
    21. public boolean remove(int val) {
    22. if (!mySet.containsKey(val)) {
    23. return false;
    24. }
    25. int oldIdx = mySet.get(val);
    26. if (oldIdx != myList.size() - 1) {
    27. int swapVal = myList.get(myList.size() - 1);
    28. mySet.put(swapVal, oldIdx);
    29. myList.set(oldIdx, swapVal);
    30. }
    31. mySet.remove(val);
    32. myList.remove(myList.size() - 1);
    33. return true;
    34. }
    35. /** Get a random element from the set. */
    36. public int getRandom() {
    37. return myList.get(rand.nextInt(myList.size()));
    38. }
    39. }
    40. /**
    41. * Your RandomizedSet object will be instantiated and called as such:
    42. * RandomizedSet obj = new RandomizedSet();
    43. * boolean param_1 = obj.insert(val);
    44. * boolean param_2 = obj.remove(val);
    45. * int param_3 = obj.getRandom();
    46. */