Conversation
| def subarraySum(self, nums: List[int], k: int) -> int: | ||
| count = 0 | ||
| total = 0 | ||
| cumsum_to_freq = defaultdict(int) |
There was a problem hiding this comment.
変数名に現れる英単語は省略しないのが好みです: cumulative_sum_to_frequencyなど.
この辺は人によるとも思うので他の方の意見も伺いたいです.
There was a problem hiding this comment.
同じく英単語は省略しないほうが好みです。以下のコメントもご参照ください。
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 |
There was a problem hiding this comment.
この部分にはあまりget()を用いるメリットがないように思います.Step1のcumsum_to_freq[total] += 1のほうがわかりやすいと感じました.
There was a problem hiding this comment.
total が cumsum_to_freq に含まれていない場合 KeyError になると思います。
|
|
||
| return count | ||
| ``` | ||
| 以上のプログラムだとTLEになる. |
There was a problem hiding this comment.
TLE と判断したのは、実際に LeetCode 上で実行して TLE になったためでしょうか?
走らせる前に、時間計算量からおおよその実行時間を推測することをおすすめします。推測方法については以下のコメントをご参照ください。
#16 (comment)
| def subarraySum(self, nums: List[int], k: int) -> int: | ||
| count = 0 | ||
| total = 0 | ||
| cumsum_to_freq = defaultdict(int) |
There was a problem hiding this comment.
同じく英単語は省略しないほうが好みです。以下のコメントもご参照ください。
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 |
There was a problem hiding this comment.
total が cumsum_to_freq に含まれていない場合 KeyError になると思います。
解く問題
Subarray Sum Equals K
次に解く問題
Number Of Islands