Insert Delete GetRandom O(1) - Duplicates allowed -LintCode

原创 2018年04月17日 20:56:32

Design a data structure that supports all following operations in average O(1) time.

 注意事项
Duplicate elements are allowed.
1. insert(val): Inserts an item val to the collection.
2. remove(val): Removes an item val from the collection if present.
3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

样例

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

思路
基本思路还是构建数组v来存放元素,这样可以实现随机等概率访问。执行insert(val)操作时,要把元素添加到v的末尾,同时构建数据结构来存放val对应的在v中的位置。执行remove(val)操作时,如果val的最大位置不在v的末尾,将val最大位置的值为v的末尾的值,为了保证取到val的最大位置,用最大堆来存放位置。

#ifndef C954_H
#define C954_H
#include<iostream>
#include<vector>
#include<unordered_map>
#include<queue>
#include<stdlib.h>
#include<algorithm>
using namespace std;
class RandomizedCollection {
public:
    /** Initialize your data structure here. */
    RandomizedCollection() {

    }

    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    bool insert(int val) {
        // write your code here
        //将元素添加到v的尾部
        //m[val]中添加其位置
        bool res = m.find(val) == m.end();
        v.push_back(val);
        m[val].push(v.size() - 1);
        return res;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        // write your code here
        if (m.find(val) == m.end())
            return false;
        //当要去除的值val不在v的尾部,将val所在的最大位置用来存放v的尾部
        //删除在m中v.back()的最大位置.将v.back()的新位置添加到m[v.back()]
        //删除在m中val的最大位置,删除v的最后一个元素
        if (val != v.back())
        {
            v[m[val].top()] = v.back();
            m[v.back()].pop();
            m[v.back()].push(m[val].top());
        }
        m[val].pop();
        v.pop_back();
        return true;
    }

    /** Get a random element from the collection. */
    int getRandom() {
        // write your code here
        //利用rand()返回v中任意位置上的元素
        if (v.empty())
            return 0;
        return v[rand() % v.size()];
    }
    unordered_map<int, priority_queue<int>> m;//存放元素的值和在v中的位置(从大到小)
    vector<int> v;//为保证getRandom()得到的结果可能性相同,将元素存入vector中
};

/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
#endif
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohengchuan/article/details/79980677

[leetcode] 381. Insert Delete GetRandom O(1) - Duplicates allowed

Design a data structure that supports all following operations in average O(1) time. Note: Duplicat...
  • TstsUgeg
  • TstsUgeg
  • 2016-08-19 16:47:31
  • 780

【Leetcode】Insert Delete GetRandom O(1)

题目链接:https://leetcode.com/problems/insert-delete-getrandom-o1/ 题目: Design a data structure tha...
  • yeqiuzs
  • yeqiuzs
  • 2016-08-07 09:14:08
  • 3403

Leetcode 381. Insert Delete GetRandom O(1) - Duplicates allowed 可重复常数增删改系统 解题报告

1 解题思想这道题是380的进化版,其实也就是在插入的时候允许了重复的值,变的更加复杂了一些。 这道题是基于这题来的,所以请先看下这题,我只说下如何从380过渡到381 Leetcode 380....
  • MebiuW
  • MebiuW
  • 2016-09-17 16:19:55
  • 1023

<leetcode>381. Insert Delete GetRandom O(1) - Duplicates allowed

381. Insert Delete GetRandom O(1) - Duplicates allowed Design a data structure that supports all fo...
  • Vipin_Pei
  • Vipin_Pei
  • 2016-09-14 21:02:03
  • 386

【Leetcode】Insert Delete GetRandom O(1) - Duplicates allowed

题目链接:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ 题目: Design a...
  • yeqiuzs
  • yeqiuzs
  • 2016-08-09 22:19:11
  • 2250

[leetcode] 380. Insert Delete GetRandom O(1) 解题报告

题目链接: https://leetcode.com/problems/insert-delete-getrandom-o1/ Design a data structure that su...
  • qq508618087
  • qq508618087
  • 2016-08-21 04:43:04
  • 2179

LeetCode:381 Insert Delete GetRandom O(1)

381. Insert Delete GetRandom O(1) - Duplicates allowed Design a data structure that supports all f...
  • Wisimer
  • Wisimer
  • 2016-08-13 12:30:23
  • 500

Leetcode 380. Insert Delete GetRandom O(1)

Using ArrayList's get function to implement getRandom() in constant time, and a hashmap to save the ...
  • u011094114
  • u011094114
  • 2017-04-02 02:54:23
  • 245

【leetcode】Insert Delete GetRandom O(1)

Insert Delete GetRandom O(1)问题描述Design a data structure that supports all following operations in av...
  • zgljl2012
  • zgljl2012
  • 2016-08-05 15:28:09
  • 1276

[leetcode] 380. Insert Delete GetRandom O(1)

Design a data structure that supports all following operations in average O(1) time. insert(v...
  • TstsUgeg
  • TstsUgeg
  • 2016-08-16 15:36:27
  • 1161
收藏助手
不良信息举报
您举报文章:Insert Delete GetRandom O(1) - Duplicates allowed -LintCode
举报原因:
原因补充:

(最多只允许输入30个字)