slice 去重
博客专区 > solate 的博客 > 博客详情
slice 去重
solate 发表于11个月前
slice 去重
  • 发表于 11个月前
  • 阅读 31
  • 收藏 0
  • 点赞 1
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

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

共有 人打赏支持
粉丝 6
博文 102
码字总数 79587
×
solate
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: