merges two integer slices, returning slices without duplicate elements, with two deduplication strategies
1. Filter repeating elements through a double loop (time-to-space)
Filter repeating elements through a double loop
func removerepbyloop (SLC []int) []int {
Result: = []int{} //store result for
I: = Range slc{
Flag: = True
for j: = Range result{
if slc[i] = = Result[j] {
flag = False //duplicate element exists, id false
break
}
}
If flag { //id = False, do not add result
= Append (result, slc[i])}
}
return Result
}
2. Filter by dictionary (space change time)
Because the primary key of the dictionary is unique, it can be used to determine whether the element is duplicated
The unique attribute of the map primary key filters The repeating element
func removerepbymap (SLC []int) []int {
Result: = []int{}
Tempmap: = map[int]byte{} //store non-repeating primary key
for _, E: = Range slc{
L: = Len (tempmap)
tempmap[e] = 0
If len (tempmap)! = l{ //Join map After the map length changes, the element does not repeat
result = Append (result, e)}
}
return result
}
PS: Here to save memory, use Map[int]byte. Because the value of map is not used, so what type can be. efficiency First, if the calculation time is saved, you can use the following method
Element de-heavy
func removerep (SLC []int) []int{
If Len (SLC) < 1024x768 {
//slice length less than 1024, loop to filter
return Removerepbyloop (SLC)
}else{
//greater than when the
return Removerepbymap (SLC)
} is filtered by map
ps:1024 This number is not particularly accurate, I am using GO Test benchmark, manual comparison. About this number of super, use map mode faster, less than this order of magnitude, loop way faster, and save memory.