Design a data structure that supports all following operations in O(1) time.

insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

分析:

因为要求所有操作O(1),插入可以满足这个条件,如果用数组来存储值,getRandom可以满足O(1).但是要求不能重复和delete的时候也满足这个条件,只能使用一个map. key是值,value是位置。

 public class RandomizedSet {
ArrayList<Integer> nums;//值
// value to position
HashMap<Integer, Integer> valueToPositionMap;
Random rand; public RandomizedSet() {
nums = new ArrayList<>();
valueToPositionMap = new HashMap<>();
rand = new Random(System.currentTimeMillis());
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean isContained = valueToPositionMap.containsKey(val);
if ( isContained ) return false;
valueToPositionMap.put( val, nums.size());
nums.add(val);
return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
boolean isContained = valueToPositionMap.containsKey(val);
if ( ! isContained ) return false;
int position = valueToPositionMap.get(val);
if (position != nums.size() - ) {
// put the true last one to 'position' in nums
int lastOne = nums.get(nums.size() - );
nums.set( position , lastOne );
valueToPositionMap.put(lastOne, position);
}
valueToPositionMap.remove(val);
nums.remove(nums.size() - );
return true;
} /** Get a random element from the set. */
public int getRandom() {
return nums.get( rand.nextInt(nums.size()) );
}
}

第二种情况:允许有重复数值。

用set来记录同一个值出现的位置,如果被删除的数不是最后一个,则和最后一个换一下位置,然后删除就可以了。

 public class RandomizedCollection {
List<Integer> nums;
Map<Integer, Set<Integer>> valueToPositionMap;
Random rand; public RandomizedCollection() {
nums = new ArrayList<>();
valueToPositionMap = new HashMap<>();
rand = new Random(System.currentTimeMillis());
} /**
* Inserts a value to the collection. Returns true if the collection did not
* already contain the specified element.
*/
public boolean insert(int val) {
boolean isContained = valueToPositionMap.containsKey(val);
if (!isContained) {
valueToPositionMap.put(val, new HashSet<>());
}
valueToPositionMap.get(val).add(nums.size());
nums.add(val);
return !isContained;
} /**
* Removes a value from the collection. Returns true if the collection contained
* the specified element.
*/
public boolean remove(int val) {
if (!valueToPositionMap.containsKey(val)) {
return false;
}
if (!valueToPositionMap.get(val).contains(nums.size() - )) {
int currPos = valueToPositionMap.get(val).iterator().next();
int lastVal = nums.get(nums.size() - );
valueToPositionMap.get(lastVal).remove(nums.size() - );
valueToPositionMap.get(lastVal).add(currPos);
valueToPositionMap.get(val).remove(currPos);
valueToPositionMap.get(val).add(nums.size() - );
nums.set(currPos, lastVal);
}
valueToPositionMap.get(val).remove(nums.size() - );
if (valueToPositionMap.get(val).isEmpty()) {
valueToPositionMap.remove(val);
}
nums.remove(nums.size() - );
return true;
} /** Get a random element from the collection. */
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}

Insert Delete GetRandom O(1) I & II的更多相关文章

  1. [LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  2. [LeetCode] Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  3. LeetCode 380. Insert Delete GetRandom O(1)

    380. Insert Delete GetRandom O(1) Add to List Description Submission Solutions Total Accepted: 21771 ...

  4. 381. Insert Delete GetRandom O(1) - Duplicates allowed

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  5. [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  6. [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  7. [LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  8. [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  9. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed

    原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...

随机推荐

  1. localdb

    <connectionStrings> - <add name="default" connectionString="Data Source=.; I ...

  2. Tomcat编码问题及访问软链接文件设置

    Tomcat编码问题及访问软链接文件设置 一.编码问题:让其支持UTF-8格式 修改tomcat中server.xml Connector port=" protocol="org ...

  3. 浅谈JavaScript中的Ajax

    引言 作为一名WEB开发者,我想Ajax技术是一定需要掌握的.你也许平时没有使用JavaScript真正的写过Ajax.但是你一定使用过JQuery里面的相关函数来进行异步调用.今天我们就来介绍下原生 ...

  4. 3步完成chrome切换搜索引擎

    1.打开chrome://settings/,找到搜索 2.点击“管理搜索引擎”,出现弹窗. 增加搜索引擎,三个文本框分别输入:名称.快捷键.地址 3.在新的选项卡中,输入快捷键(如:github), ...

  5. 今天讲的是JQ 的动画效果

    老规矩,先贴代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...

  6. js 的强制 类型 转换cast, 伪对象?

    拼音输入法简单快捷, 但是重码多, 所以要看清了再选择, 不然会影响输入正确性和 心情的! js的类型 隐式 转换? 是指, 根据 表达式的操作符号 如if(), + , && , j ...

  7. LINUX下搭建VPN

    一.准备 需要 dkms-2.0.17.5-1.noarch.rpm.ppp-2.4.5-33.0.rhel6.x86_64.rpm.pptpd-1.4.0-1.el6.x86_64.rpm,并依次安 ...

  8. JAVA访问权限控制[zhuan]

    Java的访问权限控制修饰符,从最大权限到最小权限依次是:public.protected.包访问权限(默认,没有关键字)和private.对于类的访问权限只能是:public和包访问权限(但内部类可 ...

  9. 系列文章:老项目的#iPhone6与iPhone6Plus适配#(持续更新中,更新日期2014年10月12日 星期日 )

    本文永久地址为http://www.cnblogs.com/ChenYilong/p/4020399.html ,转载请注明出处. ********************************** ...

  10. iOS: 聊聊 Designated Initializer(指定初始化函数)

    iOS: 聊聊 Designated Initializer(指定初始化函数) 一.iOS的对象创建和初始化 iOS 中对象创建是分两步完成: 分配内存 初始化对象的成员变量 我们最熟悉的创建NSOb ...