From 7c26aba0e1d9ba38a631eb5dbae8577890deb2d2 Mon Sep 17 00:00:00 2001 From: Falldio <1031249495@qq.com> Date: Sun, 17 Apr 2022 11:59:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880209.=E9=95=BF?= =?UTF-8?q?=E5=BA=A6=E6=9C=80=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84?= =?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0Kotlin=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0209.长度最小的子数组.md | 31 +++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 82a11381..fd72cf1b 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -198,7 +198,7 @@ JavaScript: var minSubArrayLen = function(target, nums) { // 长度计算一次 const len = nums.length; - let l = r = sum = 0, + let l = r = sum = 0, res = len + 1; // 子数组最大不会超过自身 while(r < len) { sum += nums[r++]; @@ -260,12 +260,12 @@ Rust: ```rust impl Solution { - pub fn min_sub_array_len(target: i32, nums: Vec) -> i32 { + pub fn min_sub_array_len(target: i32, nums: Vec) -> i32 { let (mut result, mut subLength): (i32, i32) = (i32::MAX, 0); let (mut sum, mut i) = (0, 0); - + for (pos, val) in nums.iter().enumerate() { - sum += val; + sum += val; while sum >= target { subLength = (pos - i + 1) as i32; if result > subLength { @@ -364,7 +364,7 @@ int minSubArrayLen(int target, int* nums, int numsSize){ int minLength = INT_MAX; int sum = 0; - int left = 0, right = 0; + int left = 0, right = 0; //右边界向右扩展 for(; right < numsSize; ++right) { sum += nums[right]; @@ -380,5 +380,26 @@ int minSubArrayLen(int target, int* nums, int numsSize){ } ``` +Kotlin: +```kotlin +class Solution { + fun minSubArrayLen(target: Int, nums: IntArray): Int { + var start = 0 + var end = 0 + var ret = Int.MAX_VALUE + var count = 0 + while (end < nums.size) { + count += nums[end] + while (count >= target) { + ret = if (ret > (end - start + 1)) end - start + 1 else ret + count -= nums[start++] + } + end++ + } + return if (ret == Int.MAX_VALUE) 0 else ret + } +} +``` + -----------------------