【LeetCode-设计】常数时间插入、删除和获取随机元素

时间:2020-07-17 18:18:33   收藏:0   阅读:38

题目描述

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

示例:

// 初始化一个空的集合。
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();

题目链接: https://leetcode-cn.com/problems/insert-delete-getrandom-o1/

思路

使用哈希表可以常数时间的插入和删除,但是无法用常数时间获取随机数。使用数组可以实现常数时间的插入和获取随机数,但无法实现常数时间的删除。将两者结合可以实现常数时间的插入、删除、获取随机数。

数组使用 vector<int> nums 来存储数字,哈希表使用 unordered_map<int, int> hash,hash[val] = i 表示 nums 中值为 val 的元素在位置 i,也就是 nums[val] = i;

插入:

删除:

获取随机值:

代码如下:

class RandomizedSet {
public:
    /** Initialize your data structure here. */
    RandomizedSet() {
        hash.clear();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if(hash.count(val)==0){
            nums.push_back(val);
            hash[val] = nums.size()-1; // 注意是 nums.size()-1,不是 nums.size()
            return true;
        }else return false;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if(hash.count(val)!=0){
            int idx1 = hash[val];
            int idx2 = hash[nums[nums.size()-1]];
            if(idx1==nums.size()-1){  // val 就是 nums 的最后一个元素
                nums.pop_back();
                hash.erase(val);
                return true;
            }
            swap(nums[idx1], nums[idx2]);
            nums.pop_back();
            hash[nums[idx1]] = idx1;
            hash.erase(val);
            return true;
        }else return false;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        int idx = random()%nums.size();
        return nums[idx];
    }
private:
    unordered_map<int, int> hash;
    vector<int> nums;
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */

原文:https://www.cnblogs.com/flix/p/13331404.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!