slice 去重

1.Golang 删除 slice 中重复的值

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.另外一种

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语言字符串数组去重、去空

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))
}

转载于:https://my.oschina.net/solate/blog/845703

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值