go: add «2349. Design a Number Container System»
URL: https://leetcode.com/problems/design-a-number-container-system/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
96b8b4580e
commit
44e82181c3
1 changed files with 45 additions and 0 deletions
45
go/design-a-number-container-system.go
Normal file
45
go/design-a-number-container-system.go
Normal file
|
@ -0,0 +1,45 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
pq "github.com/emirpasic/gods/v2/queues/priorityqueue"
|
||||
)
|
||||
|
||||
type NumberContainers struct {
|
||||
mapping map[int]int
|
||||
indices map[int]*pq.Queue[int]
|
||||
}
|
||||
|
||||
func Constructor() NumberContainers {
|
||||
return NumberContainers{
|
||||
mapping: make(map[int]int),
|
||||
indices: make(map[int]*pq.Queue[int]),
|
||||
}
|
||||
}
|
||||
|
||||
func (this *NumberContainers) Change(index int, number int) {
|
||||
this.mapping[index] = number
|
||||
|
||||
indices, ok := this.indices[number]
|
||||
if !ok {
|
||||
indices = pq.New[int]()
|
||||
this.indices[number] = indices
|
||||
}
|
||||
indices.Enqueue(index)
|
||||
}
|
||||
|
||||
func (this *NumberContainers) Find(number int) int {
|
||||
indices, ok := this.indices[number]
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
|
||||
for idx, ok := indices.Peek(); ok; idx, ok = indices.Peek() {
|
||||
if this.mapping[idx] == number {
|
||||
return idx
|
||||
}
|
||||
|
||||
indices.Dequeue()
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue