Skip to content

49. Group Anagrams#1

Merged
ryoooooory merged 3 commits intomainfrom
task/49
Mar 27, 2024
Merged

49. Group Anagrams#1
ryoooooory merged 3 commits intomainfrom
task/49

Conversation

@ryoooooory
Copy link
Copy Markdown
Owner

@ryoooooory
Copy link
Copy Markdown
Owner Author

回答を見るとさらに計算量のいいやり方があり、アルゴリズムをしっかり考えるとでそうな感じもあるのでできるようにしておこうと思いました。かつa-zの数が有限26個であることを利用する問題も結構みたことあるので、この考えがすぐでるようにしようと思います。

@@ -0,0 +1,24 @@
class Solution {
// 計算量は毎回ソートが入るので、文字列の長さのmaxをl, 配列の長さをnとすると、l*logl * n と予測
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

計算量を書く際は、オーダー表記を用いて、 O(l log l n) などと書くことをお勧めいたします。

class Solution {
// 計算量は毎回ソートが入るので、文字列の長さのmaxをl, 配列の長さをnとすると、l*logl * n と予測
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<>();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

変数名には、その変数の値がプログラム中でどのような役割を持っているのかを端的に表す英単語・英語句を付けることをお勧めします。これは、ソースコードを読んだ人が、最速で正確にコードの内容を理解できるようにするためです。ソースコードを読む人のペルソナが、ネイティブアメリカンイングリッシュスピーカーで、かつコンピューターサイエンスに関する学部出身であることを念頭に置き、そういった人たちに対して書くことを意識するとよいと思います。
ここではアナグラムによってグループ化されていることを表すため、 grouped または groupedByAnagrams などとするとよいと思います。

// 計算量は毎回ソートが入るので、文字列の長さのmaxをl, 配列の長さをnとすると、l*logl * n と予測
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こちらも上記と同様です。 sortedToGroupIndices 等が良いと思います。

list.get(index).add(str);
} else {
map.put(sorted, list.size());
List<String> newList = new ArrayList<>();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

新しく作られたグループであることを意図するため newGroup 等の名前を付けるとよいと思います。

Arrays.sort(cs);
String sorted = new String(cs);
if (map.containsKey(sorted)) {
int index = map.get(sorted);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

index だけでもグループのインデックスであることが伝わりますが、より叙述的にするため、 groupIndex としても良いと思います。

@ryoooooory ryoooooory merged commit c98a072 into main Mar 27, 2024
@rihib rihib mentioned this pull request Jun 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants