leetcode380-常数时间插入、删除和获取随机元素

原题

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

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

示例:

// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();

// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);

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

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

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

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

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

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

解法

思想

  1. 初始想法

哈希表的插入删除的时间复杂度都是O(1),获取的时候可以通过EntrySet。
所以这道题是不能用HashSet的。

这样虽然获取随机元素的时候时间复杂度最高可能是O(n),但仍比遍历一遍Set转ArrayList好很多。

  1. 正确解法

哈希表插入和删除都是O(1),而顺序表随机访问则是O(1),可以使用ArrayList来存储所有的数据。但是必须解决ArrayList删除元素的O(n)问题。

于是可以:

在哈希表中用value-index来记录值和在list中的下标的对应关系,如图所示

leetcode380-常数时间插入、删除和获取随机元素

当删除元素时,size减一,用list中最后那个元素替换要删除的那个元素,并且将哈希表中的对应关系改过来(用要删除的元素的index替换list中最后那个元素对应的index):

leetcode380-常数时间插入、删除和获取随机元素

此时若要随机访问元素,只需获取list中前3(size)个元素中的一个。

那么如果需要继续插入元素,只需从list中下标为3(size)处替换掉后面那个元素或是在后面那个元素之前插入(这里如果用插入是使用add(index,value)方法,个人觉得比起set会增加时间复杂度,因为使用add后面的元素都需要向后移动,虽然jdk源码中使用了System.arraycopy即内存拷贝来优化,但是也比直接替换的时间复杂度更高):

leetcode380-常数时间插入、删除和获取随机元素

如果不是替换元素而是add操作,这里会变成1-4-2-8-4

代码

  1. 初始想法
class RandomizedSet {
    Object none = new Object();
    HashMap<Integer,Object> map;
    Random random;
    /** Initialize your data structure here. */
    public RandomizedSet() {
        map = new HashMap<>();
        random = 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) {
        if(map.containsKey(val)) return false;
        map.put(val,none);
        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;
        map.remove(val);
        return true;
    }

    /** Get a random element from the set. */
    public int getRandom() {
        int ran = random.nextInt(map.size());  
        int n = 0;
        for(Map.Entry<Integer,Object> i:map.entrySet()){
            if(n==ran) return i.getKey();
            n++;
        }
        return 0;
    }
}

/**
 * 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();
 */
  1. 正确解法(来源:leetcode用户,添加元素时是直接插入)
class RandomizedSet {

    Map<Integer,Integer> map; // 存放值和在 list 的下标位置的映射
    List<Integer> list;       // 存放要插入数据的结构
    int size;                 // 数据的长度
    /** Initialize your data structure here. */
    public RandomizedSet() {
        map = new HashMap<>();
        list = new ArrayList<>();
        size = 0;
    }

    /** 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;
        else{
            // 插入数据,并更新 map 的映射后将长度加一
            list.add(size,val);
            map.put(val,size++);
            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;
        else if( size == 0 ){ map.remove(val);}
        else{
            // 取到 list 末尾的数据
            int tailKey = list.get(size-1);
            // 然后将要原先 map 中得 val-index 映射改为 tailKey-index
            map.put(tailKey,map.get(val));
            // 在 map 中取得 val 在 list 的位置,然后根据这个位置用末尾元素 tailKey 替代
            list.set(map.get(val),tailKey);
            // 在 map 中删除 val 的映射
            map.remove(val);
            size--;
        }
        return true;
    }

    /** Get a random element from the set. */
    public int getRandom() {
        Random rand = new Random();
         // rand.nextInt(size) 产生的是 0 到 size(不包括 size) 的数据
        return list.get(rand.nextInt(size));
    }
}
type RandomizedSet struct {
    Value2Index map[int]int
    List []int
}


func Constructor() RandomizedSet {
    return RandomizedSet{
        Value2Index: map[int]int{},
        List: []int{},
    }
}


func (this *RandomizedSet) Insert(val int) bool {
    _, ok := this.Value2Index[val] 
    if ok {
        return false
    }
    this.List = append(this.List, val)
    this.Value2Index[val] = len(this.List) - 1
    return true
}


func (this *RandomizedSet) Remove(val int) bool {
    index, ok := this.Value2Index[val] 
    if !ok {
        return false
    }
    delete(this.Value2Index, val)

    length := len(this.List)
    if length > 0{
        // 把最后一个元素填补到要删除的元素位置上
        lastPosValue := this.List[length - 1]
        this.List = this.List[0:length - 1]
        // 如果要删的元素本身就是最后一个元素,清空数组即可
        if index != length - 1{
            this.List[index] = lastPosValue
            this.Value2Index[lastPosValue] = index
        }
    } 
    return true
}


func (this *RandomizedSet) GetRandom() int {
    length := len(this.List)
    if length == 0{
        return 0
    }
    return this.List[rand.Intn(length)]
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode380-%e5%b8%b8%e6%95%b0%e6%97%b6%e9%97%b4%e6%8f%92%e5%85%a5%e3%80%81%e5%88%a0%e9%99%a4%e5%92%8c%e8%8e%b7%e5%8f%96%e9%9a%8f%e6%9c%ba%e5%85%83%e7%b4%a0/

(0)
彭晨涛彭晨涛管理者
上一篇 2019年12月28日
下一篇 2019年12月29日

相关推荐

  • leetcode23-合并K个排序链表

    原题 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->…

    算法 2020年2月4日
    0170
  • 程序员面试金典17.16-按摩师

    原题(来源Leetcode) 一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,…

    算法 2020年3月24日
    0930
  • leetcode1013-将数组分成和相等的三个部分

    原题 给你一个整数数组 A,只有可以将其划分为三个和相等的非空部分时才返回 true,否则返回 false。 形式上,如果可以找出索引 i+1 < j 且满足 (A[0] +…

    算法 2020年3月11日
    0560
  • leetcode198-打家劫舍

    原题 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会…

    算法 2020年5月29日
    060
  • leetcode7-整数反转

    原题 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 示例1: 输入: 123 输出: 321 示例2: 输入: -123 输出: -321 示例3: 输…

    算法 2020年2月26日
    0120
  • leetcode841-钥匙和房间

    原题 有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 在形式上,对于每个房间 i 都有一…

    2019年12月13日
    0120
  • leetcode191-位1的个数

    原题 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 示例 1: 输入: 000000000000000000000000…

    算法 2020年4月15日
    0120
  • leetcode1413-逐步求和得到正数的最小值

    原题 给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。 你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums…

    算法 2020年6月21日
    03010
  • leetcode123-买卖股票的最佳时机III

    原题 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你…

    算法 2020年6月16日
    01540
  • leetcode84-柱状图中最大的矩形

    原题 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 求在该柱状图中,能够勾勒出来的矩形的最大面积。 以上是柱状图的示例,其中每个柱子的宽…

    2020年1月24日
    0130

发表回复

登录后才能评论