Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Python3/209. Minimum Size Subarray Sum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
## Step 1. Initial Solution

- 全体としてはsubarrayのleft, rightを動かしながらminimal_lengthを更新していけば良さそう
- window_sumを保持しておくのが計算も効率的
- 実行前にコードを上から読み直して、minimal_lengthを十分大きくして、見つからなかった場合の処理も追加

```python
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
minimal_length = len(nums) + 1
Copy link

Choose a reason for hiding this comment

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

minimal_ や minimum_number_of_ は、 min_ と略すことが多いように思います。他に

  • num_(number of)
  • sum_(sum of)
  • max_(maximum number of)

などもよく使うように思います。このあたりは、所属するチームの平均的な書き方に合わせることをおすすめします。

left = 0
window_sum = 0
Copy link

Choose a reason for hiding this comment

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

自分なら sum_nums または sum_nums_in_window と名付けると思いますが、趣味の範囲だと思います。

for right, num in enumerate(nums):
window_sum += num
while window_sum >= target and left <= right:
minimal_length = min(minimal_length, right - left + 1)
window_sum -= nums[left]
left += 1

if minimal_length == len(nums) + 1:
return 0
return minimal_length
```

### Complexity Analysis

- 時間計算量:O(N)
- 空間計算量:O(1)

## Step 2. Alternatives

- https://github.com/tokuhirat/LeetCode/pull/49/files
- 最短長をmath.infで初期化している
- 未更新時もmath.isinfでチェック
- 型も違うし敢えて極端に大きい数にする必要もないような気がする
- フラグを置く方が未更新判定のところで前を読み直す必要はなくなりそう
- leftごとに走査しているものもあるが非効率
- ほぼ同じ
- https://github.com/Mike0121/LeetCode/pull/22/files
- 0が入っているときにどうするかは自分も少し考えていた
- https://github.com/olsen-blue/Arai60/pull/50/files#r2005919622
- 0が入ってくるだけなら満たす範囲で最小を探しに行くので問題ない
- 負の数が入ってくるとどうか
- 累積和がマイナスになったらleftをその向こう側に持っていけば良いくらいで一応そのままでも動きそう

## Step 3. Final Solution

- 最初とほぼ同じ実装

```python
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
minimal_length = len(nums) + 1
left_index = 0
subarray_sum = 0
for right_index in range(len(nums)):
subarray_sum += nums[right_index]
while subarray_sum >= target and left_index <= right_index:
minimal_length = min(minimal_length, right_index - left_index + 1)
subarray_sum -= nums[left_index]
left_index += 1
if minimal_length == len(nums) + 1:
return 0
return minimal_length
```

Choose a reason for hiding this comment

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

読みやすいです。