Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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で簡単に実行できる)。出力結果を見ると、容量と配列の位置が変わらないのがわかる。
対して、
var s []int
を使ってみると、容量が足りなくなるたびに倍の容量が新たに確保され、配列のアドレス位置も変わっていることがわかる。なのでこの場合は配列を新たに確保し、要素を新しい配列にコピーする形になる。