Go数组去重

时间:2025-03-31 21:00:27

整数数组去重

// 通过map键的唯一性去重
func RemoveRepeatedElement(s []int) []int {
	result := make([]int, 0)
	m := make(map[int]bool) //map的值不重要
	for _, v := range s {
		if _, ok := m[v]; !ok {
			result = append(result, v)
			m[v] = true
		}
	}
	return result
}

func TestDup(t *testing.T) {
	arr := []int{1, 2, 3, 3}
	r := RemoveRepeatedElement(arr)
	t.Log(r)
	// [1 2 3]
}

字符串数组去重

// RemoveDuplicatesAndEmpty 移除数组中重复元素
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
}