Golang--slice element de-weight

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.