Skip to content

Instantly share code, notes, and snippets.

@namtx
Created April 28, 2020 09:31
Show Gist options
  • Select an option

  • Save namtx/c666e0f4386489daabc927f0fe4d3e0d to your computer and use it in GitHub Desktop.

Select an option

Save namtx/c666e0f4386489daabc927f0fe4d3e0d to your computer and use it in GitHub Desktop.
list.Remove issue
package main
import (
"container/list"
"fmt"
)
type FirstUnique struct {
nums []int
m map[int]*list.Element
l *list.List
}
func Constructor(nums []int) FirstUnique {
m := map[int]*list.Element{}
l := new(list.List)
for _, n := range nums {
if node, ok := m[n]; ok {
l.Remove(node)
} else {
element := &list.Element{Value: n}
l.PushBack(element)
m[n] = element
}
}
return FirstUnique{
nums: nums,
m: m,
l: l,
}
}
func (this *FirstUnique) ShowFirstUnique() int {
return this.l.Front().Value.(*list.Element).Value.(int)
}
func (this *FirstUnique) Add(value int) {
this.nums = append(this.nums, value)
if node, ok := this.m[value]; ok {
this.l.Remove(node)
} else {
element := &list.Element{Value: value}
this.l.PushBack(element)
this.m[value] = element
}
}
func main() {
obj := Constructor([]int{3, 5, 2, 3})
fmt.Println(obj.ShowFirstUnique())
obj.Add(2)
fmt.Println(obj.ShowFirstUnique())
obj.Add(3)
obj.Add(5)
fmt.Println(obj.ShowFirstUnique())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment