HashSet幾個簡單方法的實現
阿新 • • 發佈:2019-01-11
package main import ( "bytes" "fmt" ) type Set interface { Add(e interface{}) bool /*新增*/ Remove(e interface{}) /*刪除*/ Clear() /*清空*/ Len() int /*求長度*/ Same(other *HashSet) bool /*是否相同*/ Elements()[]interface{} /*獲取HashSet的鍵值*/ String() string /*重構String方法*/ } /*** * 實現HashSet的幾個基本方法 * */ type HashSet struct{ m map[interface{}]bool } func (set *HashSet) Add(e interface{}) bool{ if !set.m[e]{ set.m[e] = true return true } return false } func (set *HashSet) Remove(e interface{}){ delete(set.m,e) } func (set *HashSet) Clear(){ set.m = make(map[interface{}]bool) } func (set *HashSet) Contains(e interface{}) bool{ return set.m[e] } func (set *HashSet) Len() int{ return len(set.m) } func (set *HashSet) Same(other *HashSet) bool{ if other == nil{ return false } if set.Len() != other.Len(){ return false } for key := range set.m{ if !other.Contains(key){ return false } } return true } func (set *HashSet) Elements() []interface{}{ initialLen := len(set.m) snapshot := make([]interface{},initialLen) actualLen := 0 for key:= range set.m{ if actualLen < initialLen{ snapshot[actualLen] = key }else{ snapshot = append(snapshot,key) } actualLen++ } if actualLen<initialLen{ snapshot = snapshot[:actualLen] } return snapshot } func (set *HashSet) String() string{ var buf bytes.Buffer buf.WriteString("Set{") first := true for key:= range set.m{ if first { first = false }else{ buf.WriteString(" ") } buf.WriteString(fmt.Sprintf("%v",key)) } buf.WriteString("}") return buf.String() } func (set *HashSet) IsSuperset(other *HashSet) bool{ if other == nil{ return false } oneLen := set.Len() otherLen := other.Len() if oneLen == 0 || oneLen == otherLen{ return false } if oneLen>0 && otherLen == 0{ return true } for _,v := range other.Elements(){ if !set.Contains(v){ return false } } return true } func main(){ }