当前位置:网站首页>2021-11-10:o (1) time inserts, deletes and obtains random elements. Implement ra
2021-11-10:o (1) time inserts, deletes and obtains random elements. Implement ra
2022-06-24 01:52:00 【Fuda scaffold constructor's daily question】
2021-11-10:O(1) Time insertion 、 Delete and get random elements . Realization RandomizedSet class :RandomizedSet() initialization RandomizedSet object .bool insert(int val) When element val When there is no , Insert the item into the collection , And back to true ; otherwise , return false .bool remove(int val) When element val In existence , Remove the item from the collection , And back to true ; otherwise , return false .int getRandom() Random return of an item in an existing collection ( The test case guarantees that there is at least one element in the collection when this method is called ). Every element should have Same probability Returned . You must implement all the functions of the class , And satisfy the of each function Average The time complexity is O(1) . Power button 380.
answer 2021-11-10:
Two hash tables .
v→index.
index→v.
index It must be continuous .
Delete the element in the middle , Replace... With the last element . such index It's continuous .
The code to use golang To write . The code is as follows :
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
nrs := NewRandomizedSet()
nrs.insert(6)
nrs.insert(3)
nrs.insert(7)
nrs.insert(9)
nrs.insert(8)
fmt.Println(nrs.getRandom())
}
type RandomizedSet struct {
keyIndexMap map[int]int
indexKeyMap map[int]int
size int
}
func NewRandomizedSet() *RandomizedSet {
res := &RandomizedSet{}
res.keyIndexMap = make(map[int]int)
res.indexKeyMap = make(map[int]int)
res.size = 0
return res
}
func (this *RandomizedSet) insert(val int) bool {
if _, ok := this.keyIndexMap[val]; !ok {
this.keyIndexMap[val] = this.size
this.indexKeyMap[this.size] = val
this.size++
return true
}
return false
}
func (this *RandomizedSet) remove(val int) bool {
if _, ok := this.keyIndexMap[val]; ok {
deleteIndex := this.keyIndexMap[val]
this.size--
lastIndex := this.size
lastKey := this.indexKeyMap[lastIndex]
this.keyIndexMap[lastKey] = deleteIndex
this.indexKeyMap[deleteIndex] = lastKey
delete(this.keyIndexMap, val)
delete(this.indexKeyMap, lastIndex)
return true
}
return false
}
func (this *RandomizedSet) getRandom() int {
if this.size == 0 {
return -1
}
randomIndex := rand.Intn(this.size)
return this.indexKeyMap[randomIndex]
}The results are as follows :
边栏推荐
- Application analysis of video edge computing gateway easynvr in video overall monitoring solution
- Tcapulusdb database: the king behind the "Tianya Mingyue swordsman Tour"
- [guide to cloud first] point north before tdsql elite challenge
- 4-data persistence and shared interconnection
- An error is reported when easynvr uploads the SSL certificate: the network request fails. How to handle it?
- Oracle sqlldr quick import and sqluldr2 quick export
- Tcapulusdb Jun · industry news collection
- Qu'est - ce que le financement des pensions? Quels sont les produits financiers pour les personnes âgées?
- Using nginscript as a file distribution service with permission
- [SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)
猜你喜欢

It's too difficult for me. Ali has had 7 rounds of interviews (5 years of experience and won the offer of P7 post)
![[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)](/img/c8/f6c2a62b8ab8fa88bd2b3d8f35f592.jpg)
[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)
![[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)](/img/b5/a8c4bbaf868dd20b7dc9449d2a4378.jpg)
[SQL injection 13] referer injection foundation and Practice (based on burpseuite tool and sqli labs less19 target platform)

I, a 27 year old female programmer, feel that life is meaningless, not counting the accumulation fund deposit of 430000
随机推荐
How to create a group on a barcode label
Qu'est - ce que le financement des pensions? Quels sont les produits financiers pour les personnes âgées?
LeetCode 1289. Descent path min and II
tokio_ Rustls self signed certificate
Interviewer: let's talk about the snowflake algorithm. The more detailed, the better
Typescript type system
Nature Reviews Neuroscience: cognitive and behavioral flexibility - neural mechanisms and clinical considerations
Tcapulusdb Jun · industry news collection
[tcapulusdb knowledge base] how to clean up tables in tcapulusdb table management?
Go language core 36 lectures (go language practice and application VII) -- learning notes
4、 Variable assignment method
Tcapulusdb Jun · industry news collection
SAP WM displays the standard report lx09 of TR item
Intensive use of glusterfs 4.1
4-data persistence and shared interconnection
How does the education industry realize the TRTC interactive classroom apaas solution under the "double reduction policy"?
Easycvr connects with Huawei IVS platform to query the foreign domain list interface definition and use sharing
[new function!] How anycast CLB supports multi location & dynamically accelerated load balancing services and high-speed Internet forwarding!
SAP mm maintains inter company sto error -no delivery type defined for supplying
DCOM horizontal movement of Intranet penetration