Skip to content

Conversation

@rihib
Copy link
Owner

@rihib rihib commented Jun 25, 2024

Group Anagramsを解きました。レビューお願いいたします。

言語:Go
問題:https://leetcode.com/problems/group-anagrams/description/

anagrams := make([][]string, len(anagramsMap))は、代わりにanagrams := make([][]string, 0, len(anagramsMap))として長さ0、容量len(anagramsMap)anagramsを定義することで、anagrams = append(anagrams, words)と新たなメモリ割り当てをせずに書くことができる。

スライスは内部的には配列が使われていてそのポインタを移動させているだけなので、容量を指定すればその容量分の長さの配列が確保され、それを超えない限りは再度アロケーションされることはない。

実際に確かめるために下記のコードを実験してみる(Go Playgroundで簡単に実行できる)。出力結果を見ると、容量と配列の位置が変わらないのがわかる。

package main

import (
	"fmt"
	"unsafe"
)

func main() {
	s := make([]int, 0, 5)
	// var s []int
	printSlice(s)

	for i := 1; i <= 5; i++ {
		s = append(s, i)
		printSlice(s)
	}
}

func printSlice(s []int) {
	if len(s) > 0 {
		fmt.Printf("len=%d cap=%d address=%p %v\n", len(s), cap(s), unsafe.Pointer(&s[0]), s)
	} else {
		fmt.Printf("len=%d cap=%d address=nil %v\n", len(s), cap(s), s)
	}
}
len=0 cap=5 address=nil []
len=1 cap=5 address=0xc00011c000 [1]
len=2 cap=5 address=0xc00011c000 [1 2]
len=3 cap=5 address=0xc00011c000 [1 2 3]
len=4 cap=5 address=0xc00011c000 [1 2 3 4]
len=5 cap=5 address=0xc00011c000 [1 2 3 4 5]

対して、var s []intを使ってみると、容量が足りなくなるたびに倍の容量が新たに確保され、配列のアドレス位置も変わっていることがわかる。なのでこの場合は配列を新たに確保し、要素を新しい配列にコピーする形になる。

len=0 cap=0 address=nil []
len=1 cap=1 address=0xc000012060 [1]
len=2 cap=2 address=0xc000012070 [1 2]
len=3 cap=4 address=0xc00007c020 [1 2 3]
len=4 cap=4 address=0xc00007c020 [1 2 3 4]
len=5 cap=8 address=0xc00007e040 [1 2 3 4 5]

ちなみに、makeの引数に、mapを作る場合は型とキャパシティのヒントの2つのみを取ることができる。スライスを作る場合は型と長さとキャパシティのヒントの3つを取ることができる。

@rihib rihib merged commit 0534b84 into main Sep 23, 2024
@rihib rihib deleted the group_anagrams branch September 23, 2024 12:45
rihib added a commit that referenced this pull request Mar 31, 2025
rihib added a commit that referenced this pull request Mar 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants