func(s *MyHashSet) Remove(key int) { if !s.Contains(key) { return } idx := key % len(s.arr) for i, v := range s.arr[idx] { if v == key { s.arr[idx] = remove(s.arr[idx], i) return } } }
/** Returns true if this set contains the specified element */ func(s *MyHashSet) Contains(key int) bool { idx := key % len(s.arr) for _, v := range s.arr[idx] { if key == v { returntrue } } returnfalse }
/** * Your MyHashSet object will be instantiated and called as such: * obj := Constructor(); * obj.Add(key); * obj.Remove(key); * param_3 := obj.Contains(key); */
删除slice中的元素
Order matters
If you want to keep your array ordered, you have to shift all of the elements at the right of the deleting index by one to the left. Hopefully, this can be done easily in Golang:
1 2 3
funcremove(slice []int, s int) []int { returnappend(slice[:s], slice[s+1:]...) }
However, this is inefficient because you may end up with moving all of the elements, which is costy.
Order is not important
If you do not care about ordering, you have the much faster possibility to swap the element to delete with the one at the end of the slice and then return the n-1 first elements: