slice 去重

2019-07-22 17:50:58 浏览数 (1)

1.Golang 删除 slice 中重复的值

代码语言:javascript复制
package main

import (
	"fmt"
)

func main() {
	a := []int{2, 1, 2, 5, 6, 3, 4, 5, 2, 3, 9}
	UniqueSlice(&a)
	fmt.Println(a)


}

func UniqueSlice(slice *[]int) {
	found := make(map[int]bool)
	total := 0
	for i, val := range *slice {
		if _, ok := found[val]; !ok {
			found[val] = true
			(*slice)[total] = (*slice)[i]
			total  
		}
	}

	*slice = (*slice)[:total]
}


func UniqueSlice_2(slice *[]string) {
    found := make(map[string]bool)
    total := 0
    for i, val := range *slice {
        if _, ok := found[val]; !ok {
            found[val] = true
            (*slice)[total] = (*slice)[i]
            total  
        }
    }

    *slice = (*slice)[:total]
}


func UniqueSlice_3(slice *[]int) []int {
	found := make(map[int]bool)
	result := []int{}
	for _, val := range *slice {
		if _, ok := found[val]; !ok {
			found[val] = true
			result = append(result, val)

		}
	}

	return result
}

2.另外一种

代码语言:javascript复制
package main

import (
	"fmt"
)

func main() {
	a := []int{2, 1, 2, 5, 6, 3, 4, 5, 2, 3, 9}
	z := Rm_duplicate(&a)
	fmt.Println(z)


}

func Rm_duplicate(list *[]int) []int {
	var x []int = []int{}
	for _, i := range *list {
		if len(x) == 0 {
			x = append(x, i)
		} else {
			for k, v := range x {
				if i == v {
					break
				}
				if k == len(x)-1 {
					x = append(x, i)
				}
			}
		}
	}
	return x
}

3.GO语言字符串数组去重、去空

代码语言:javascript复制
package main
 
import(
    "fmt"
    "sort"
)
 
func RemoveDuplicatesAndEmpty(a []string) (ret []string){
    a_len := len(a)
    for i:=0; i < a_len; i  {
        if (i > 0 && a[i-1] == a[i]) || len(a[i])==0{
            continue;
        }
        ret = append(ret, a[i])
    }
    return
}
 
func main(){
    a := []string{"hello", "", "world", "yes", "hello", "nihao", "shijie", "hello", "yes", "nihao","good"}
    sort.Strings(a)
    fmt.Println(a)
    fmt.Println(RemoveDuplicatesAndEmpty(a))
}

0 人点赞