golang string slice deduplication

The function of the function is to remove duplicate elements from the input string slice and return the deduplicated result. The specific implementation logic is as follows:

  1. Create an empty result slice resultfor storing deduplicated strings.
  2. Create a temporary map tempMapfor storing unique strings. The keys of the map are strings and the values ​​are bytes.
  3. slcIterate over each element in the input string slice e:
    • First, get tempMapthe length and assign it to a variable l.
    • Then, use the string eas the key, set the value to 0, and store it tempMapin.
    • If the length of is changed tempMapafter the addition (that is, an element that does not exist is successfully added), it means that the element appears for the first time and is not repeated.tempMap
      • Append this element eto the result slice result.
  4. After traversing all elements, return the result slice result, which is the result after deduplication.
// 通过map主键唯一的特性过滤重复元素
func RemoveDuplicateStrings(strs []string) []string {
    result := []string{}
    tempMap := map[string]byte{} // 存放不重复字符串
    for _, e := range strs {
        l := len(tempMap)
        tempMap[e] = 0
        if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复
            result = append(result, e)
        }
    }
    return result
}

Guess you like

Origin blog.csdn.net/taoshihan/article/details/132353780