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

本文描述了一个数据结构设计问题,要求实现一个集合类,支持在平均时间复杂度为O(1)的情况下执行插入、删除和随机获取元素的操作。解决方案利用哈希表和线性表,哈希表用于存储元素及其索引,线性表保持元素顺序,随机数生成器用于随机返回元素。
摘要由CSDN通过智能技术生成

https://leetcode.cn/problems/FortPu/

题目要求

设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构:
insert(val):当元素 val 不存在时返回 true ,并向集合中插入该项,否则返回 false 。
remove(val):当元素 val 存在时返回 true ,并从集合中移除该项,否则返回 false 。
getRandom:随机返回现有集合中的一项。每个元素应该有 相同的概率 被返回。

方法:Hash表+线性表

  • 使用hash表来存储val和对应的index下标,同时可以使用containsKey来判断是某个元素已经存在
  • 使用线性表来保存元素,元素和下标是一一对应的
    List<Integer> list;
    Map<Integer, Integer> map;
    Random rd;

    /** Initialize your data structure here. */
    public RandomizedSet() {
        list = new ArrayList<>();
        map = new HashMap<>();
        rd = 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) {
        // val已存在
        if (map.containsKey(val)) return false;
        // 插入
        int index = list.size();
        list.add(val);
        map.put(val, index);
        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 n = list.size() - 1;
        int last = list.get(n);// 获取最后一个元素
        list.set(index, last);// 最后一个元素覆盖删除元素
        map.put(last, index);// last的index是删除元素的index
        list.remove(n);// 删除最后一个元素
        map.remove(val);// 删除map中的val
        return true;
    }

    /** Get a random element from the set. */
    public int getRandom() {
        return list.get(rd.nextInt(list.size()));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值