插入、删除和随机访问都是 O(1) 的容器(剑指offer 您所在的位置:网站首页 随机访问直接访问 插入、删除和随机访问都是 O(1) 的容器(剑指offer

插入、删除和随机访问都是 O(1) 的容器(剑指offer

2024-07-13 13:21| 来源: 网络整理| 查看: 265

原题链接

题目描述

设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构:

insert(val):当元素 val 不存在时返回 true ,并向集合中插入该项,否则返回 false 。 remove(val):当元素 val 存在时返回 true ,并从集合中移除该项,否则返回 false 。 getRandom:随机返回现有集合中的一项。每个元素应该有 相同的概率 被返回

示例1

输入: inputs = [“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”] [[], [1], [2], [2], [], [1], [2], []] 输出: [null, true, false, true, 2, true, false, 2] 解释: RandomizedSet randomSet = new RandomizedSet(); // 初始化一个空的集合 randomSet.insert(1); // 向集合中插入 1 , 返回 true 表示 1 被成功地插入

randomSet.remove(2); // 返回 false,表示集合中不存在 2

randomSet.insert(2); // 向集合中插入 2 返回 true ,集合现在包含 [1,2]

randomSet.getRandom(); // getRandom 应随机返回 1 或 2

randomSet.remove(1); // 从集合中移除 1 返回 true 。集合现在包含 [2]

randomSet.insert(2); // 2 已在集合中,所以返回 false

randomSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2

思路

能实现O(1)复杂度插入和删除的数据结构只有哈希表。但是如果只用哈希表,无法等概率随机返回某个值,而随机返回某个值可以用数组实现,先随机出一个随机数(在0~length - 1内),作为下标,然后返回对应的值即可。 所以我们选用哈希表+数组。

Map map = new HashMap(); List list = new ArrayList(); 插入

HashMap中的key对应要插入的值,value对应该值在数组中的下标,因为要O(1)插入,所以我们不能移动数组中的数,所以直接插入在数组的末尾,即 map.put(val, list.size()),然后将其加入到数组,即list.add(val)

删除

这个步骤多一点,我们不能直接list.remove(map.get(val))!! 为什么呢? 因为如果我们要删除的元素不在数组的末尾,那么删掉他之后,list会自动把他空出的位置补全,即把他后面的元素都向前移动,那么就不符合O(1)的复杂度了。 所以想一下,只有删除末尾的元素是O(1)复杂度,所以我们只需要将这个元素和末尾元素进行互换,然后再删掉他即可。 所以先从map中找出他的下标index,然后在map中重新put以list末尾的值为key,index为value的数据,然后把list中index位置的值设位list末尾的那个数,然后再从map和list中都把val移除即可

随机访问

直接随机一个0~list.size() - 1 的数,然后返回list中对应的数即可

完整代码 class RandomizedSet { /** Initialize your data structure here. */ Map map; List list; public RandomizedSet() { map = new HashMap(); list = new ArrayList(); } /** 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) { if(!map.containsKey(val)){ return false; } int index = map.get(val); int last = list.get(list.size() - 1); map.put(last, index); map.remove(val); list.set(index, last); list.remove(list.size() - 1); return true; } /** Get a random element from the set. */ public int getRandom() { Random random = new Random(); int index = random.nextInt(list.size()); return list.get(index); } } /** * 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(); */


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有