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. git命令之git tag 给当前分支打标签

    git tag - 标签相关操作 发表于 2011年06月29日 由 机器猫 标签可以针对某一时间点的版本做标记,常用于版本发布. 列出标签 $ git tag # 在控制台打印出当前仓库的所有标签$ ...

  2. bootstrap-select去除蓝色边框outline

    /*去除选择框的outline*/ .bootstrap-select .dropdown-toggle:focus{outline:none !important;} /*去除选项的outline* ...

  3. Druid使用起步—在javaWeb项目中配置监控 连接池

    当我们在javaWEB项目中使用到druid来作为我们的连接池的时候,一定不会忘了添加监控功能.下面我们就来看一下,在一个简单的web项目中(尚未使用任何框架)我们是如果来配置我们的web.xml来完 ...

  4. 装X之写博客

    博客作用: 为了温习以前的知识,记录下 前几天和一个前辈聊天,说起看书总是前面学後面忘点的事情· 写个博客试试?

  5. Linq→join中指定多个条件

    还是习惯先撸一段SQL * FROM User_Pic P AND P.Guid = R.UserPicGuid ORDER BY PicSize DESC 然后发现Linq中的join不能多条件.. ...

  6. VTK初学一,a Mesh from vtkImageData—球冠

    #ifndef INITIAL_OPENGL #define INITIAL_OPENGL #include <vtkAutoInit.h> VTK_MODULE_INIT(vtkRend ...

  7. Android 实现简单音乐播放器(一)

    今天掐指一算,学习Android长达近两个月了,今天开始,对过去一段时间的学习收获以及遇到的疑难杂症做一些总结. 简单音乐播放器是我自己完成的第一个功能较为完整的APP,可以说是我的Android学习 ...

  8. C 语言sscanf

    C语言以sscanf逗号作为分割符 ]={}; ]={}; ]={}; sscanf(],&buf_b[],&buf_b[]); printf("************** ...

  9. IE8 margin: auto 无法居中

    需要给body元素添加属性 body { text-align: center; width: 100%; } ok,可以正常居中.

  10. Mysql BLOB和TEXT类型

      BLOB是一个二进制大对象,可以容纳可变数量的数据.有4种BLOB类型:TINYBLOB.BLOB.MEDIUMBLOB和LONGBLOB.它们只是可容纳值的最大长度不同. A binary la ...