Skip to content

560. Subarray Sum Equals K#21

Open
Yuto729 wants to merge 2 commits intomainfrom
subarray-sum-equals-k
Open

560. Subarray Sum Equals K#21
Yuto729 wants to merge 2 commits intomainfrom
subarray-sum-equals-k

Conversation

@Yuto729
Copy link
Owner

@Yuto729 Yuto729 commented Dec 24, 2025

解く問題

Subarray Sum Equals K

次に解く問題

Number Of Islands

@Yuto729 Yuto729 changed the title Subarray Sum Equals K 560. Subarray Sum Equals K Dec 24, 2025
def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
total = 0
cumsum_to_freq = defaultdict(int)
Copy link

Choose a reason for hiding this comment

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

変数名に現れる英単語は省略しないのが好みです: cumulative_sum_to_frequencyなど.
この辺は人によるとも思うので他の方の意見も伺いたいです.

Copy link

Choose a reason for hiding this comment

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

同じく英単語は省略しないほうが好みです。以下のコメントもご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)

if total - k in cumsum_to_freq:
count += cumsum_to_freq[total - k]

cumsum_to_freq[total] = cumsum_to_freq.get(total, 0) + 1
Copy link

Choose a reason for hiding this comment

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

この部分にはあまりget()を用いるメリットがないように思います.Step1のcumsum_to_freq[total] += 1のほうがわかりやすいと感じました.

Copy link

Choose a reason for hiding this comment

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

total が cumsum_to_freq に含まれていない場合 KeyError になると思います。


return count
```
以上のプログラムだとTLEになる.
Copy link

Choose a reason for hiding this comment

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

TLE と判断したのは、実際に LeetCode 上で実行して TLE になったためでしょうか?
走らせる前に、時間計算量からおおよその実行時間を推測することをおすすめします。推測方法については以下のコメントをご参照ください。
#16 (comment)

def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
total = 0
cumsum_to_freq = defaultdict(int)
Copy link

Choose a reason for hiding this comment

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

同じく英単語は省略しないほうが好みです。以下のコメントもご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)

if total - k in cumsum_to_freq:
count += cumsum_to_freq[total - k]

cumsum_to_freq[total] = cumsum_to_freq.get(total, 0) + 1
Copy link

Choose a reason for hiding this comment

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

total が cumsum_to_freq に含まれていない場合 KeyError になると思います。

Repository owner deleted a comment from github-actions bot Dec 26, 2025
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