常数时间插入删除和获取随机元素

Posted Alice_yufeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常数时间插入删除和获取随机元素相关的知识,希望对你有一定的参考价值。

class RandomizedSet 
  Map<Integer, Integer> dict;
  List<Integer> list;
  Random rand = new Random();

  /** Initialize your data structure here. */
  public RandomizedSet() 
    dict = new HashMap();
    list = new ArrayList();
  

  /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
  public boolean insert(int val) 
    if (dict.containsKey(val)) return false;

    dict.put(val, list.size());
    list.add(list.size(), val);
    return true;
  

  /** Removes a value from the set. Returns true if the set contained the specified element. */
  public boolean remove(int val) 
    if (! dict.containsKey(val)) return false;

    // move the last element to the place idx of the element to delete
    int lastElement = list.get(list.size() - 1);
    int idx = dict.get(val);
    list.set(idx, lastElement);
    dict.put(lastElement, idx);
    // delete the last element
    list.remove(list.size() - 1);
    dict.remove(val);
    return true;
  

  /** Get a random element from the set. */
  public int getRandom() 
    return list.get(rand.nextInt(list.size()));
  

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

以上是关于常数时间插入删除和获取随机元素的主要内容,如果未能解决你的问题,请参考以下文章

常数时间插入删除和获取随机元素

常数时间插入删除和获取随机元素

380. O 时间插入删除和获取随机元素

题目地址(1/“>380. O 时间插入删除和获取随机元素)

LeetCode 0381. O 时间插入删除和获取随机元素 - 允许重复

LeetCode 0381. O 时间插入删除和获取随机元素 - 允许重复