Conversation
| numToIdx[n] = i | ||
| } | ||
|
|
||
| log.Panic("No valid pair found.") |
There was a problem hiding this comment.
シグネチャを変える必要があるのでleetcode上では出来ない気がしますが、Goではエラーを返すことが一般的かと思います。
また、その場でプログラム全体を停止させたい場合は、例えば以下のように書けますね。
log.Fatal("No valid pair found.")
panic("unreachable")panic自体はスレッド(正確にはゴルーチン)を停止させます。
There was a problem hiding this comment.
Fatal は、os.Exit 呼ぶので、次の行の panic は不要ではないでしょうか。
https://pkg.go.dev/log#Fatal
There was a problem hiding this comment.
こちらの panic はコンパイラに unreachable であることを伝えるために置いています。
この用法については以下に記述があります。
https://google.github.io/styleguide/go/best-practices.html#when-to-panic
Panic is also used when the compiler cannot identify unreachable code, for example when using a function like log.Fatal that will not return:
| func twoSum(nums []int, target int) []int { | ||
| numToIdx := make(map[int]int) | ||
| for i, n := range nums { | ||
| dif := target - n |
There was a problem hiding this comment.
この変数は多分 difference の略語だと思うのですが、diff とするのが一般的だと思います
| numToIdx := make(map[int]int) | ||
| for i, n := range nums { | ||
| dif := target - n | ||
| if _, exist := numToIdx[dif]; exist { |
There was a problem hiding this comment.
okはサンプルコードでよく見かけましたが、これで伝わるのかなと思ってしまい、existを使っていました。でも、慣習には従った方が良さそうですね
| for i, n := range nums { | ||
| dif := target - n | ||
| if _, exist := numToIdx[dif]; exist { | ||
| return []int{i, numToIdx[dif]} |
There was a problem hiding this comment.
numToIdx[dif]ではなく、76行目でif j, ok := numToIdx[dif]; ok {などのようにしてあげるとreturn []int{i, j}とすっきり書けます
There was a problem hiding this comment.
そうするとdifが使われる箇所が一箇所だけになるので、dif自体の宣言をやめて、76行目でそのままnumToIdx[target-n]のようにしてしまっても良いかなと思いました。
| - こういった身体性を持つというか、実世界に例えてみる想像力はアルゴリズムを思いつくときに非常に有用だなと思った | ||
| - 答えが存在しない場合にpanicするコードを書いている人を見かけたので、自分もやってみることに | ||
| - 以前からleetcodeをやっているとエラーハンドリングについてのセンスが磨かれないなという点を問題点だと思っていた | ||
|
|
There was a problem hiding this comment.
調べごとをする癖もここで身につけたいことです。
エラーハンドリングは、死ぬか、エクセプションを投げるか、あとは無理やり返すか、などで状況によるでしょう。
https://leetcode.com/problems/two-sum/description/