博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 380: Insert Delete GetRandom O(1)
阅读量:6947 次
发布时间:2019-06-27

本文共 1712 字,大约阅读时间需要 5 分钟。

class RandomizedSet {        Map
indexMap; List
indexes; /** Initialize your data structure here. */ public RandomizedSet() { indexes = new ArrayList<>(); indexMap = new HashMap<>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if (indexMap.containsKey(val)) { return false; } indexMap.put(val, indexes.size()); indexes.add(val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if (!indexMap.containsKey(val)) { return false; } int index = indexMap.get(val); if (index < indexes.size() - 1) { indexMap.put(indexes.get(indexes.size() - 1), index); indexes.set(index, indexes.get(indexes.size() - 1)); } indexMap.remove(val); indexes.remove(indexes.size() - 1); return true; } /** Get a random element from the set. */ public int getRandom() { return indexes.get(new Random().nextInt(indexes.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(); */

Follow up questions, what if dup allows:

1. Map<Value, Queue<Indexes>> if it looks like a queue first in first out.

2. Map<Value, Map<Index, Indexes>> User can remove the nth value.

转载于:https://www.cnblogs.com/shuashuashua/p/7452779.html

你可能感兴趣的文章
[转]SQLITE3 C语言接口 API 函数简介
查看>>
Delphi XE5中使用jar包
查看>>
org.apache.felix.framework-5.6.12源码解析——org.apache.felix.framework文件夹最后的部分...
查看>>
Python3的tcp socket接收不定长数据包接收到的数据不全。
查看>>
b2b
查看>>
第三周Java学习总结
查看>>
OGRE的安装和编译【转+改】
查看>>
获取管理员组用户
查看>>
Mysql—(2)—
查看>>
简历的分布式
查看>>
[转]string和stringstream用法总结
查看>>
LeetCode:Rotate Array
查看>>
jquery pagination.js 分页
查看>>
DOM对象与jquery对象
查看>>
1.6(SQL学习笔记)存储过程
查看>>
XXS level8
查看>>
分布式日志收集系统:Facebook Scribe
查看>>
VxWorks下PCI驱动的配置与测试
查看>>
NSString 中包含中文字符时转换为NSURL
查看>>
Unity 协程停不了?
查看>>