Skip to content

560. Subarray Sum Equals K#15

Open
rinost081 wants to merge 1 commit intomainfrom
LeetCode560
Open

560. Subarray Sum Equals K#15
rinost081 wants to merge 1 commit intomainfrom
LeetCode560

Conversation

@rinost081
Copy link
Copy Markdown
Owner

No description provided.

Comment thread lc560.md

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

Choose a reason for hiding this comment

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

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

Comment thread lc560.md
num_subarrays = 0
cumsum = 0
cumsum_to_count = defaultdict(int)
cumsum_to_count[0] = 1
Copy link
Copy Markdown

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が嬉しいです

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

Choose a reason for hiding this comment

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

i + 1ですかね

Comment thread lc560.md
cumsum_to_count[cumsum] += 1

return num_subarrays
```
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

読みやすかったです。

Comment thread lc560.md

- 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
Copy Markdown

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