-
Notifications
You must be signed in to change notification settings - Fork 0
Create 0209-minimum-size-subarray-sum.md #50
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: main
Are you sure you want to change the base?
Conversation
| - うーん、いきなりsliding windowでやったから再検討が必要。 | ||
| - まず原点回帰して、最もナイーブには全探索で、O(n^2)となる。 | ||
| - しかし、内側のループは無駄が多そう。 | ||
| - 前からの累積和は単調増加するので、二分探索(lower bound)で初めて和がtarget以上になる点がわかる。 |
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.
ありがとうございます。
書いてみました。
class Solution:
def minSubArrayLen(self, target: int, nums: list[int]) -> int:
if target <= 0:
raise ValueError(f"target '{target}' must be positive")
if not nums:
return 0
INF = len(nums) + 1
def calc_min_length(left, right):
if left == right:
if nums[left] >= target:
return 1
return INF
mid = (left + right) // 2
left_min_length = calc_min_length(left, mid)
right_min_length = calc_min_length(mid + 1, right)
min_length = min(left_min_length, right_min_length)
i = mid
j = mid + 1
total = 0
# invariant: total = sum(nums[i:j])
while i >= left:
total += nums[i]
while total < target and j <= right:
total += nums[j]
j += 1
if total >= target:
min_length = min(min_length, j - i)
i -= 1
return min_length
min_length = calc_min_length(0, len(nums) - 1)
if min_length == INF:
return 0
return min_length| for left in range(len(nums)): | ||
| right = bisect.bisect_left(prefix_sum, target + prefix_sum[left]) | ||
| if right == len(prefix_sum): | ||
| continue |
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.
break でいいでしょうか?
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.
ありがとうございます。
breakでいいですね。
この問題:https://leetcode.com/problems/minimum-size-subarray-sum/
次の問題:https://leetcode.com/problems/permutations/