380. Insert Delete GetRandom O(1)

Link

Solution

透過HashMap來記錄每個node的位置,以及判斷重複與否

在delete時,將被刪除的元素以最後的元素進行替換,並更新map

  /** Initialize your data structure here. */
    Map<Integer, Integer> map;
    List<Integer> list;
    Random r;
    public RandomizedSet() {
        map = new HashMap<>();
        list = new ArrayList<>();
        r = new Random();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if(map.containsKey(val)) return false;
        map.put(val, list.size());
        list.add(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if(!map.containsKey(val)) return false;
        int loc = map.get(val);
        
        if(loc != list.size()-1){
            //swap with lastone
            int lastOne = list.get(list.size()-1);
            map.put(lastOne, loc);
            list.set(loc, lastOne);
        }
        map.remove(val);
        list.remove(list.size()-1);
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        
        return list.get(r.nextInt(list.size()));
    }

Last updated

Was this helpful?