problem0381

package
v0.0.0-...-db5e768 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2019 License: MIT Imports: 2 Imported by: 0

README

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

题目

Design a data structure that supports all following operations in average O(1) time. Note: 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.

Example:

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

解题思路

见程序注释

感谢 LeetCode 服务器,又多了一个100% 381

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RandomizedCollection

type RandomizedCollection struct {
	// contains filtered or unexported fields
}

RandomizedCollection 是一个随机获取的集合

func Constructor

func Constructor() RandomizedCollection

Constructor returns RandomizedSet Initialize your data structure here.

func (*RandomizedCollection) GetRandom

func (r *RandomizedCollection) GetRandom() int

GetRandom 获取随机数据 Get a random element from the collection.

func (*RandomizedCollection) Insert

func (r *RandomizedCollection) Insert(val int) bool

Insert 插入数据 Inserts a value to the collection. Returns true if the collection did not already contain the specified element.

func (*RandomizedCollection) Remove

func (r *RandomizedCollection) Remove(val int) bool

Remove 删除数据 Removes a value from the collection. Returns true if the collection contained the specified element.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL