Skip to content

560. Subarray Sum Equals K #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

560. Subarray Sum Equals K #15

wants to merge 1 commit into from

Conversation

rinost081
Copy link
Owner

No description provided.


for num in nums:
cumsum += num
if cumsum - k in cumsum_to_count:
Copy link

Choose a reason for hiding this comment

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

defaultdictを使うのであればこの条件分岐はなくてもいいかもしれません。
(defaultdictは評価された時点で辞書の中に値が入るので、条件分岐をしておくと無駄に辞書の中身が増えないという利点はありますが)

num_subarrays = 0
cumsum = 0
cumsum_to_count = defaultdict(int)
cumsum_to_count[0] = 1
Copy link

Choose a reason for hiding this comment

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

多分好みの問題なのですが,自分はここはcumsum_to_count[cumsum] = 1が嬉しいです

complement = k - nums[i]
if complement == 0:
num_subarrays += 1
for j in range(i+1, len(nums)):
Copy link

Choose a reason for hiding this comment

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

i + 1ですかね

cumsum_to_count[cumsum] += 1

return num_subarrays
```

Choose a reason for hiding this comment

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

読みやすかったです。


- https://github.com/potrue/leetcode/pull/16/files?short_path=9af6c29#diff-9af6c29cdcdd4f79ab8b011317151f6cd8b13f570a036eb4d7473388bc3f0d56
- chainを使って解いているがchainについて初めて見たので[ドキュメント]()https://docs.python.org/ja/3.13/library/itertools.html#itertools.chainを見る

Copy link

Choose a reason for hiding this comment

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

ドキュメントを読むのはいい癖だと思います。

それから読む先ですが完走者の中で気に入った人を見繕っておいてもいいかと思います。

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.

5 participants