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

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

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1); // Returns false as 2 does not exist in the set.
randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2); // getRandom should return either 1 or 2 randomly.
randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1); // 2 was already in the set, so return false.
randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

Solution1:  HashMap + ArrayList

1. use an ArrayList together with HashMap, making hashmap save key(item)->value(idx)

2. To reverse item in O(1), avoiding traversal the whole arrayList in O(n) time, we swap the toDelete item with last item in the list

3. Go through an example like this:

use HashMap to get removeIdx:

Set the last item in the list as replaceValue, why the last item? In order to maintain other indices.

Deal with HashMap: (1) put  (2)delete

Deal with List: (1) set  (2)delete

code:

 class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> list;
Random r; // java 自带类 /** Initialize your data structure here. */
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
r = new Random();
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (map.containsKey(val)) {
return false;
}
map.put(val, list.size());
list.add(val);
return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
/**
hashmap
30 - 0
40 - 1
50 - 2
60 - 3 list: 30 40 50 60
0 1 2 3
**/
if (!map.containsKey(val)) return false;
int removeIdx = map.get(val); // Idx: 1
int replaceValue = list.get(list.size()-1); // replaceValue : 60 // deal with map
map.put(replaceValue, removeIdx);
map.remove(val); // deal with list
list.set(removeIdx, replaceValue);
list.remove(list.size() -1); return true;
} /** Get a random element from the set. */
public int getRandom() {
return list.get(r.nextInt(list.size()));
}
}

[leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值的更多相关文章

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

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

  2. LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)

    题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...

  3. [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 ...

  4. [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 ...

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

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

  6. [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 ...

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

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

  8. leetcode 380. Insert Delete GetRandom O(1) 、381. Insert Delete GetRandom O(1) - Duplicates allowed

    380. Insert Delete GetRandom O(1) 实现插入.删除.获得随机数功能,且时间复杂度都在O(1).实际上在插入.删除两个功能中都包含了查找功能,当然查找也必须是O(1). ...

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

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

随机推荐

  1. PythonStudy——编程基础 Python Primary

    1.什么是编程语言 语言:  一个事物与另外一个事物沟通的介质 .编程语言是程序员与计算机沟通的介质. 编程: 将人类内识别的语言转化为机器能识别的指令,这种过程就叫做编程. 注:最终这些指令会被转化 ...

  2. lua tasklib 之lumen 分析

    sched.sleep分析 sleep会填充M.running_task.waitds数据表示当前task需要等待,最后yield出去到主线程 M.sleep = function (timeout) ...

  3. DataSource - 常用数据库连接池 (DBCP、c3p0、Druid) 配置说明

    1. 引言 1.1 定义 数据库连接是一种关键的有限的昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出.对数据库连接的管理能显著影响到整个应用程序的伸缩性和健壮性,影响到程序的性能指标.数据库 ...

  4. Flask--(项目准备)--添加日志

    日志:记录程序运行的状态,在manage.py同级目录下创建logs文件夹 定义日志文件: import logging from logging.handlers import RotatingFi ...

  5. python成功之道

    https://blog.ansheng.me/article/python-full-stack-way

  6. Core Graphices 获取上下文

    Core Graphices 获取上下文的三种方式: 1.自定义view 重写view 的 drawRect:(CGRect)rect方法 - (void)drawRect:(CGRect)rect ...

  7. Linux 上利用Nginx代理uWSGI处理Flask web应用

    一.介绍 最近开发要用一个测试环境,是这样的Nginx+uwsgi+flask 的一个结构.下面是一些记录,在Centos 系统上使用Flask 架构部署一个简单的Python应用.然后使用Nginx ...

  8. python3 kmp 字符串匹配

    先声明,本人菜鸟一个,写博客是为了记录学习的过程,以及自己的理解和心得,可能有的地方写的不好,希望大神指出... 抛出问题 给定一个文本串test_str(被匹配的字符串)和模式串pat_str(需要 ...

  9. 实战ELK(7)ElasticSearch常用的基本查询语句

    1.term 过滤 term主要用于精确匹配哪些值,比如数字,日期,布尔值或 not_analyzed 的字符串(未经切词的文本数据类型): { "term": { "d ...

  10. !!代码:baidu 分享

    改参数,可以改图标的尺寸:16x16.24x24.32x32 <!DOCTYPE html> <html> <head> <title></tit ...