1 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
最直接和易于理解的解決方案是使用映射 - 如果您只使用鍵,丟棄值,它們與許多其他集合實(shí)現(xiàn)(O(1)查找*,唯一鍵,無序)共享相似的屬性。在這一點(diǎn)上,它實(shí)際上非常簡(jiǎn)單:
func Difference(slice1 []string, slice2 []string) []string {
// Create proper "set" (Maps have unordered pairs and the keys are unique;
// lookup to check whether value is present is O(1), similar to other
// implementations)
m := make(map[string]struct{}, len(slice1))
for _, el := range slice1 {
m[el] = struct{}{}
}
// Remove values from slice1 present in slice2
for _, el := range slice2 {
delete(m, el)
}
// Note that res will be non-deterministic: the order of iteration over maps
// is made random on purpose by Go itself
res := make([]string, 0, len(m))
for k := range m {
res = append(res, k)
}
return res
}
添加回答
舉報(bào)