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

题目

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

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

示例 :

输入: 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 
 

提示:

-231 <= val <= 231 - 1
最多进行 2 * 105 次 insert , remove 和 getRandom 方法调用
当调用 getRandom 方法时,集合中至少有一个元素
 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/FortPu
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

思路:题目需求O(1)时间复杂度内的增删和随机访问,使用数组来存储数据实现增删,使用hashmap来存储元素对应下标以实现随机访问。

注意,java的arraylist的remove有两个重载方法,一个是传入val,一个是传入index,传入时可以通过如下方式区别:

remove(1)   //是删除索引为1的元素
remove(new Integer(1))  //则删除元素1
tips:注意删除时,要将list的最后一位元素替补上来,否则,list会自动补齐,这时存储在indices中的<val,index>中的index会自动减少一位,出现error。使用list.set(index,val)补过来之后记得将最后一位元素删除remove(list.size())。

代码:

class RandomizedSet {

	List<Integer> list;
	Map<Integer,Integer> indices;
    
    /** Initialize your data structure here. */
    public RandomizedSet() {
    	list=new ArrayList<>();
    	indices= 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(indices.get(val)!=null) 
    		return false;
    	else
    		list.add(val);
    		indices.put(val, list.size()-1);
    		return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {//删除元素之后将最后一个元素替补上来,否则后续所有的元素下标会发生混乱。
    	if(indices.get(val)!=null) {
    		int index=indices.get(val);
    		int lastValue=list.get(list.size()-1);
    		list.set(index, lastValue);
    		indices.put(lastValue, index);
    		list.remove(list.size()-1);
    		indices.remove(val);
    		return true;
    	}else {
    		return false;
    	}
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
    	int index=(int)(Math.random()*list.size());//底层调用的是random类的nextdouble方法。
    	return list.get(index);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值