// author:zfy date:2023/3/23
package main
import "fmt"
// 直接操作数组
func removeItem(a []int, elem int) []int {
j := 0
for _, v := range a {
if v != elem {
a[j] = v
j++
}
}
return a[:j]
}
// 新建一个数组unc removeItem1(a []int, elem int) []int {
var aNew []int
for _, v := range a {
if v != elem {
aNew = append(aNew, v)
}
}
return aNew
}
func main() {
a := []int{1, 2, 3, 4}
elem := 2
fmt.Println(removeItem(a, elem))
b := []int{1, 2, 3, 4}
elemb := 2
fmt.Println(removeItem1(b, elemb))
}
golang 删除数组中的指定元素
于 2023-03-25 17:59:17 首次发布