-
Notifications
You must be signed in to change notification settings - Fork 0
Group Anagrams #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
+126
−0
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Owner
Author
Ryotaro25
reviewed
Jun 25, 2024
Ryotaro25
reviewed
Jun 25, 2024
Mike0121
reviewed
Jun 25, 2024
kazukiii
reviewed
Jun 25, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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を使ってみると、容量が足りなくなるたびに倍の容量が新たに確保され、配列のアドレス位置も変わっていることがわかる。なのでこの場合は配列を新たに確保し、要素を新しい配列にコピーする形になる。ちなみに、makeの引数に、mapを作る場合は型とキャパシティのヒントの2つのみを取ることができる。スライスを作る場合は型と長さとキャパシティのヒントの3つを取ることができる。