Skip to content

Conversation

@SuperHotDogCat
Copy link
Owner

class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
cumulative_sum = [0] * (len(nums) + 1)
cumulative_sum_to_index = defaultdict(list)
Copy link

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]:
Copy link

Choose a reason for hiding this comment

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

bisect で高速化できるとは思います。ですが、 phase2 の解法が正着のように思いますので、あまりこだわらなくても良いかもしれません。

Copy link
Owner Author

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を保存したせいで沼にハマった問題をやった記憶があるな...?
Copy link

Choose a reason for hiding this comment

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

Copy link
Owner Author

Choose a reason for hiding this comment

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

maximum subarrayなども確かに同じ類ですね.....累積和だなと思ってそのまま書いたあとワンテンポ置いて動的に処理することで効率化できないか考えるようにでもしてみます

@SuperHotDogCat
Copy link
Owner Author

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.

4 participants