-
Notifications
You must be signed in to change notification settings - Fork 0
Subarray sum equals k #29
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
base: arai60
Are you sure you want to change the base?
Conversation
| class Solution: | ||
| def subarraySum(self, nums: List[int], k: int) -> int: | ||
| cumulative_sum = [0] * (len(nums) + 1) | ||
| cumulative_sum_to_index = defaultdict(list) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
index が複数格納されるため、 cumulative_sum_to_indexes または cumulative_sum_to_indicies としたほうが良いと思います。
|
|
||
| count = 0 | ||
| for i in range(len(nums) + 1): | ||
| for j in cumulative_sum_to_index[cumulative_sum[i] - k]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
bisect で高速化できるとは思います。ですが、 phase2 の解法が正着のように思いますので、あまりこだわらなくても良いかもしれません。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
あ, なるほど, 単調に増加するloop内部でcumulative_sum_to_index[cumulative_sum[i]]にappendされているのでsortされた状態になっているんですね
| hayashi-ay: https://github.com/hayashi-ay/leetcode/pull/31/files | ||
| Exzrgs: https://github.com/Exzrgs/LeetCode/commit/caa03ede122e5e1d2de4b8ebd24ee26aaf3d743b | ||
|
|
||
| なんか前も先にindexを保存しておくかfor文の中で動的に処理するかみたいなので先にindexを保存したせいで沼にハマった問題をやった記憶があるな...? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maximum subarrayなども確かに同じ類ですね.....累積和だなと思ってそのまま書いたあとワンテンポ置いて動的に処理することで効率化できないか考えるようにでもしてみます
問題
560. Subarray Sum Equals K