From 4e2c449827e3bc6a7b2e9c52803076118314f6b3 Mon Sep 17 00:00:00 2001 From: reoooh Date: Sun, 2 Jan 2022 22:36:47 +0800 Subject: [PATCH] 2022-0102: 0209 add ruby version --- problems/0209.长度最小的子数组.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 80822436..7c13961d 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -107,7 +107,7 @@ public: }; ``` -时间复杂度:$O(n)$ +时间复杂度:$O(n)$ 空间复杂度:$O(1)$ **一些录友会疑惑为什么时间复杂度是$O(n)$**。 @@ -121,7 +121,6 @@ public: - ## 其他语言版本 @@ -291,5 +290,23 @@ class Solution { } ``` +Ruby: + +```ruby +def min_sub_array_len(target, nums) + res = Float::INFINITY # 无穷大 + i, sum = 0, 0 + nums.length.times do |j| + sum += nums[j] + while sum >= target + res = [res, j - i + 1].min + sum -= nums[i] + i += 1 + end + end + res == Float::INFINITY ? 0 : res +end +``` + -----------------------