Skip to content

Commit 8f41614

Browse files
authored
Merge pull request #8 from rihib/two_sum
Two Sum
2 parents 2b4d615 + 87fcc53 commit 8f41614

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

pullrequests/two_sum/step1.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package twosum
3+
4+
/*
5+
かなり前に解いたものなので詳細は忘れてしまいましたが、ナイーブにやる方法では各文字ごとに毎回リストを走査してしまうと時間計算量がO(n^2)になってしまうので、オーバーヘッドはありますが、ハッシュ化するのが良いと考えました。
6+
7+
また同じ要素を2回使うのを避けるために、毎回追加する前に対応する要素がないかを確認してから追加するようにしました。
8+
*/
9+
func twoSumStep1(nums []int, target int) []int {
10+
m := make(map[int]int)
11+
for i, n := range nums {
12+
if j, ok := m[target-n]; ok {
13+
return []int{i, j}
14+
}
15+
m[n] = i
16+
}
17+
return nil
18+
}

pullrequests/two_sum/step2.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package twosum
3+
4+
/*
5+
mではなく、よりわかりやすいようにnumsMapとしました。
6+
GoogleのGoスタイルガイドには変数名に型名を使うのは良くないと書かれていますが、同時に下記のようにも書かれています。今回はnumsという配列をマップに変換したもの(配列もインデックスと値を情報としてもつ)と捉えることができるため、対応していることを示すためにnumsMapとしました。
7+
8+
`It is acceptable to include a type-like qualifier if there are two versions of a value in scope, for example you might have an input stored in ageString and use age for the parsed value.`
9+
10+
`numToIdx`というのもありそう(https://github.com/aoshi2025s/leetcode-review/pull/1#discussion_r1666780953)。
11+
12+
対応する組み合わせが見つからなかった際にどうするのかは難しいところ。
13+
- https://github.com/seal-azarashi/leetcode/pull/11#discussion_r1672537855
14+
- https://github.com/sendahuang14/leetcode/pull/11#discussion_r1702393602
15+
*/
16+
func twoSumStep2(nums []int, target int) []int {
17+
numsMap := make(map[int]int)
18+
for i, n := range nums {
19+
if j, ok := numsMap[target-n]; ok {
20+
return []int{i, j}
21+
}
22+
numsMap[n] = i
23+
}
24+
return nil
25+
}

pullrequests/two_sum/step3.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package twosum
3+
4+
func twoSumStep3(nums []int, target int) []int {
5+
numToIndex := make(map[int]int)
6+
for i, n := range nums {
7+
if j, ok := numToIndex[target-n]; ok {
8+
return []int{i, j}
9+
}
10+
numToIndex[n] = i
11+
}
12+
return nil // 本来ならerrorを返したい
13+
}

0 commit comments

Comments
 (0)