方法一:暴力,两层for循环——会超时

Python
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        result = len(nums) + 1
        for i in range(len(nums)):
            temp = 0
            for j in range(i, len(nums)):
                temp += nums[j]
                if temp < target:
                    continue
                else:
                    result = min(result, j - i + 1)
                    break

        if result == len(nums) + 1:
            return 0
        return result
Java
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int result = nums.length + 1;
        for (int i = 0; i < nums.length; i++) {
            int temp = 0;
            for (int j = i; j < nums.length; j++) {
                temp += nums[j];
                if (temp < target) {
                    continue;
                } else {
                    result = Math.min(result, j - i + 1);
                    break;
                }
            }
        }
        if (result == nums.length + 1) {
            return 0;
        } else {
            return result;
        }
    }
}

方法二:滑动窗口

窗口端点的移动方式:

  • 若窗口内数值的和大于等于目标值,窗口左端移动,此时可以更新窗口大小最小值
  • 若窗口内数值的和小于目标值,窗口右端移动
Python
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        left = 0
        right = 0
        result = len(nums) + 1
        sum_temp = nums[0]
        while left < len(nums) or right < len(nums):
            if sum_temp >= target:
                result = min(result, right -left + 1)
                sum_temp -= nums[left]
                left += 1
            else:
                right += 1
                if right == len(nums):
                    break
                sum_temp += nums[right]
            if result == 1:
                return result

        if result == len(nums) + 1:
            return 0
        return result
Java
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0;
        int right = 0;
        int result = nums.length + 1;
        int sum_temp = nums[0];

        while (left < nums.length || right < nums.length) {
            if (sum_temp >= target) {
                result = Math.min(result, right - left + 1);
                sum_temp -= nums[left];
                left++;
            }else {
                right ++;
                if (right == nums.length) {
                    break;
                }
                sum_temp += nums[right];
            }
            if (result == 1) {
                return 1;
            }
        }
        if (result == nums.length + 1) {
            return 0;
        }
        return result;
    }
}
posted on 2022-06-21 22:44  墩墩儿er  阅读(17)  评论(0编辑  收藏  举报