go语言数组相关

go语言数组相关换算
目前已有:交集,差集,去重
持续更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main

// 数组相关换算
// 交集,差集,去重

import (
"fmt"
)

func main() {
a := []int{98, 298, 588, 1598, 3698, 5000}
b := []int{298, 588}

// DiffArray 求两个切片的差集, 在a里面不在b里面
diff_array := DiffArray(a, b)
fmt.Println(diff_array)

// 交集
intersect_array := IntersectArray(a, b)
fmt.Println(intersect_array)

// 去重
arr := []string{"a", "a", "b", "c"}
remove_repeated := RemoveRepeatedElement(arr)
remove_repeatedq := arrayUnique(arr)
fmt.Println(remove_repeated)
fmt.Println(remove_repeatedq)

}

// DiffArray 求两个切片的差集
func DiffArray(a []int, b []int) []int {
var diffArray []int
temp := map[int]struct{}{}

for _, val := range b {
if _, ok := temp[val]; !ok {
temp[val] = struct{}{}
}
}

for _, val := range a {
if _, ok := temp[val]; !ok {
diffArray = append(diffArray, val)
}
}

return diffArray
}

// IntersectArray 求两个切片的交集
func IntersectArray(a []int, b []int) []int {
var inter []int
mp := make(map[int]bool)

for _, s := range a {
if _, ok := mp[s]; !ok {
mp[s] = true
}
}
for _, s := range b {
if _, ok := mp[s]; ok {
inter = append(inter, s)
}
}

return inter
}

//切片去重实现
func arrayUnique(arr []string) []string {
result := make([]string, 0, len(arr))
temp := map[string]struct{}{}
for i := 0; i < len(arr); i++ {
if _, ok := temp[arr[i]]; ok != true {
temp[arr[i]] = struct{}{}
result = append(result, arr[i])
}
}
return result
}

// RemoveRepeatedElement 切片去重实现
func RemoveRepeatedElement(arr []string) (newArr []string) {
newArr = make([]string, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
break
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
return
}