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. 随笔 JS 字符串 分割成字符串数组 并动态添加到指定ID的DOM 里

    JS /* * 字符串 分割成字符串数组 并动态添加到指定ID的DOM 里 * @id 要插入到DOM元素的ID * * 输入值为图片URL 字符串 * */ function addImages(i ...

  2. php实现发送邮件

    smtp.php: <?php class smtp {     /* Public Variables */     var $smtp_port;     var $time_out;    ...

  3. 【phpcms-v9】phpcms-v9二次开发所必须知道的步骤(转载)

    一.做phpcms-v9二次开发时,我们经常需要用到如下代码,所以有必须在这里注释说明一下 defined('IN_PHPCMS') or exit('No permission resources. ...

  4. java正则表达式 --简单认识

    学习目标 正则表达式的作用正则表达式的模式匹配Pattern类和Matcher类的使用掌握String对正则的支持具体内容一.认识正则(为什么要有正则) 方便的对数据进行匹配 执行复杂的字符串验证.拆 ...

  5. 将Ubuntu 15.10升级到Ubuntu 16.04

    Ubuntu 16.04 LTS 代号为 Xenial Xerus,其最终版将于 2016 年 4 月 21 日正式发布,Ubuntu16.04 将是非常受欢迎的开源操作系统 Ubuntu 的第 6 ...

  6. apt-get方式安装lnmp环境

    安装nginxsudo apt-get install nginx安装php和mysqlsudo apt-get install php5-cli php5-cgi php5-curl php5-my ...

  7. 如何判断一个变量是否是utf-8

    //判断传入的字符是否是utf-8  function is_utf8($word){   if (preg_match("/^([".chr(228)."-" ...

  8. centos 安装 mysql5.6

    转载自 http://www.cnblogs.com/littlehb/archive/2013/04/02/2995007.html Mysql 5.5以后使用了CMake进行安装,参考与以前的区别 ...

  9. RQNOJ659 计算系数

    http://www.rqnoj.cn/problem/659 描述 给定一个多项式(ax + by)^k,请求出多项式展开后x^n * y^m项的系数. 格式 输入格式 共一行,包含5个整数,分别为 ...

  10. python基础教程1

    python作为一种编程语言,诞生于1990年左右,算是一门比较年轻的语言(也算是90后吧),它是面向对象的,但不同于JAVA\C#那么严格要求一切皆对象,更接近于C++,是面向过程和面向对象的结合: ...