LeetCode Insert Delete GetRandom O(1) - Duplicates allowed

题意:设计一个数据结构,支持添加,删除和随机获取元素,允许元素重复,要求时间复杂度为O(1)

思路:因为要求允许元素重复,可能用key=>set的映射方式,其中set表示相同元素对应的下标。用list来顺序添加元素

关键是删除操作,如果删除的元素不是在list的最后一个元素,将其与最后元素交换,同时更新元素对应的位置set

更新也要按照一定的顺序来操作,删除元素对应的位置,同时更新最后一个元素的位置。因类删除的元素可能与最后一个元素相等

代码如下:

public class RandomizedCollection {

    private Map<Integer, Set<Integer>> map;
    private List<Integer> list;
    private Random random;

    /** Initialize your data structure here. */
    public RandomizedCollection() {
        map = new HashMap<>();
        list = new ArrayList<>();
        random = new Random();
    }

    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    public boolean insert(int val) {
        boolean notHasVal = true;

        if (map.containsKey(val)) notHasVal = false;

        int len = list.size();
        list.add(val);

        if (!map.containsKey(val))
        {
            Set<Integer> set = new HashSet<>();
            set.add(len);
            map.put(val, set);
        }
        else
        {
            map.get(val).add(len);
        }

        return notHasVal;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    public boolean remove(int val)
    {
        if (!map.containsKey(val)) return false;

        int index = map.get(val).iterator().next();
        int size = list.size();
        int num = 0;

        if (index != size - 1)
        {
            int tmp = list.get(index);
            num = list.get(size - 1);
            list.set(index, num);
            list.set(size - 1, tmp);
        }

        list.remove(size - 1);

        map.get(val).remove(index);
        if (index != size - 1)
        {
            map.get(num).remove(size - 1);
            map.get(num).add(index);
        }

        if (map.get(val).size() == 0)
        {
            map.remove(val);
        }

        return true;
    }

    /** Get a random element from the collection. */
    public int getRandom()
    {
        return list.get(random.nextInt(list.size()));
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值