1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go 配列の重複を取り除く

Posted at

コード

配列のまま要素ごとに重複を探索すると計算量が増えるので一旦mapにする。
mapは重複したキーの存在ができないので、再度配列に変換すると重複が取り除かれた状態で取得できる。

func distinct(arr []int) []int {
	m := make(map[int]struct{})
	for _, v := range arr {
		m[v] = struct{}{}
	}
	var newArr []int
	for k, _ := range m {
		newArr = append(newArr, k)
	}
	return newArr
}

使い方

func main() {
	fmt.Println(distinct([]int{1, 2, 3, 1})) // => [1 2 3]
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?