0
0

More than 1 year has passed since last update.

Leetcode 380. Insert Delete GetRandom O(1)

Posted at

380. Insert Delete GetRandom O(1)

アプローチ

ArrayList, HashSet

class RandomizedSet {

  public ArrayList<Integer> arrayList;
    public Set<Integer> set;
    public Random rm;
    public RandomizedSet() {
        arrayList = new ArrayList<>();
        set = new HashSet<>();
        rm = new Random();
    }

    public boolean insert(int val) {
        if(set.contains(val)){
            return false;
        }
        arrayList.add(val);
        set.add(val);
        return true;
    }

    public boolean remove(int val) {
        if(!set.contains(val)){
            return false;
        }

        set.remove(val);
        arrayList.remove(new Integer(val));
        return true;
    }

    public int getRandom() {
        int idx = rm.nextInt(set.size());
        return arrayList.get(idx);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0