Skip to content

560. Subarray Sum Equals K#16

Open
n6o wants to merge 1 commit intomainfrom
subarray-sum-equals-k
Open

560. Subarray Sum Equals K#16
n6o wants to merge 1 commit intomainfrom
subarray-sum-equals-k

Conversation

@n6o
Copy link
Owner

@n6o n6o commented Feb 13, 2026

今回の問題

Subarray Sum Equals K - LeetCode

使用言語

Go

次に解く問題

Number of Islands - LeetCode

Comment on lines +112 to +118
for _, num := range nums {
prefixSum += num
if c, found := prefixSumToCount[prefixSum - k]; found {
count += c
}
prefixSumToCount[prefixSum]++
}
Copy link

Choose a reason for hiding this comment

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

単なる感想として…

  • num までの prefixSum を求めながら、それまで登場した prefixSum - k のカウントを足すことで部分配列を数え上げる、という2つのことを同じループで処理している
  • 2つの count が登場して紛らわしい

あたりが、読解するのに苦労するなあと思いました。
※現状のコードから改善するポイントは特に思いつかないのですが

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。

改善するとしたら

  • countsubarrayCount など何の数え上げなのか明示する
  • コメントを書く

などが考えられるかなと思いました。
また時間をとって見直してみます。

Choose a reason for hiding this comment

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

num までの prefixSum を求めながら、それまで登場した prefixSum - k のカウントを足すことで部分配列を数え上げる、という2つのことを同じループで処理している

一つの方法としては、

  • prefixSum を求めるループ
  • 和が k になる subarray の数を、prefixSum から求めるループ

の二つのループに分けてしまうというのもありなのかなと思いました。

せいぜい計算量も O(n) で 言語もGoなので、計算時間としても大体数ms 犠牲にするぐらいで済むと思います。

Copy link

@TakayaShirai TakayaShirai left a comment

Choose a reason for hiding this comment

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

全体的に読みやすかったです!

Comment on lines +112 to +118
for _, num := range nums {
prefixSum += num
if c, found := prefixSumToCount[prefixSum - k]; found {
count += c
}
prefixSumToCount[prefixSum]++
}

Choose a reason for hiding this comment

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

num までの prefixSum を求めながら、それまで登場した prefixSum - k のカウントを足すことで部分配列を数え上げる、という2つのことを同じループで処理している

一つの方法としては、

  • prefixSum を求めるループ
  • 和が k になる subarray の数を、prefixSum から求めるループ

の二つのループに分けてしまうというのもありなのかなと思いました。

せいぜい計算量も O(n) で 言語もGoなので、計算時間としても大体数ms 犠牲にするぐらいで済むと思います。

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