Java O(1) 时间插入、删除和获取随机元素

实现RandomizedSet 类:

        RandomizedSet() 初始化 RandomizedSet 对象
        bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。
        bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。
        int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
        你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。

class RandomizedSet {

    static int[] nums;
    Random rand;
    HashMap<Integer,Integer> map;
    int index = -1;
    
    public RandomizedSet() {
        this.nums = new int[200001];
        this.rand = new Random();
        this.map = new HashMap<>();
    }
    
    public boolean insert(int val) {
        if( map.containsKey(val) ){
            return false;
        }
        map.put(val,++index);
        nums[index] = val;
        return true;
    }
    
    public boolean remove(int val) {
        if( !map.containsKey(val) ){
            return false;
        }
        int local = map.remove(val);

        //如果元素位置不是最后一个,交换位置
        if(local != index){
            map.put(nums[index],local);
        }
        nums[local] = nums[index--];
        return true;
    }
    
    public int getRandom() {
        return nums[rand.nextInt(index+1)];
    }
}

/**
 * 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();
 */

执行用时:22 ms, 在所有 Java 提交中击败了61.97%的用户

内存消耗:85.9 MB, 在所有 Java 提交中击败了81.16%的用户

通过测试用例:19 / 19

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值