209. Minimum Size Subarray Sum (M)

本文探讨了在给定正整数数组中寻找最短连续子数组,使其和大于等于指定值的问题。提供了两种解决方案,一种是使用滑动窗口法,时间复杂度为O(N),另一种是采用二分查找法,时间复杂度为O(NlogN)。

Minimum Size Subarray Sum (M)

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

Follow up:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).


题意

给定一个正整数s和一个正整数数组nums,要求在nums中找到一个最短的连续子序列,使其和大于等于s。

思路

**滑动窗口法(Two Pointers):**连续子数组问题很容易想到使用滑动窗口来解题。用left和right分别指向窗口的左端点和右端点,如果当前窗口内的整数和小于s,则将右端点右移来拉长窗口;如果当前窗口内的整数和大于等于s,判断其长度是否比当前结果小,是则记录,并将左端点右移来缩短窗口。重复以上步骤就能得到一个长度最短且整数和大于等于s的窗口。最坏情况下左右端点都走了一遍数组,所以时间复杂度为O(2N)=O(N)O(2N)=O(N)O(2N)=O(N)

**二分查找:**新建sum数组,sum[i]=nums[0]+...+nums[i]sum[i] = nums[0]+...+nums[i]sum[i]=nums[0]+...+nums[i],则问题转化为在数组sum中求一个连续子数组,使其末首之差大于等于s。从左向右遍历,每次固定左端点i,在右半边子数组中利用二分法找到值大于等于s+sum[i]s+sum[i]s+sum[i]的元素sum[j],判断长度并记录。时间复杂度为O(NlogN)O(NlogN)O(NlogN)


代码实现 - 滑动窗口1

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums.length == 0) {
            return 0;
        }

        int ans = 0;
        int left = 0, right = 0;
        int sum = nums[0];
        while (right < nums.length) {
            if (sum < s && right < nums.length - 1) {
                sum += nums[++right];
            } else if (sum >= s) {
                ans = ans == 0 ? right - left + 1 : Math.min(ans, right - left + 1);
                sum -= nums[left++];
            } else {
                break;	// 当右端点已经在数组的末尾且sum仍比s小时,可以直接跳出
            }
        }
        
        return ans;
    }
}

代码实现 - 滑动窗口2

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int ans = Integer.MAX_VALUE;
        int sum = 0;
        int left = 0;
        
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= s) {
                ans = Math.min(ans, right - left + 1);
                sum -= nums[left++];
            }
        }
        
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}

代码实现 - 二分查找

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums.length == 0) {
            return 0;
        }

        int ans = Integer.MAX_VALUE;
        int[] sum = new int[nums.length];
        
        for (int i = 0; i < nums.length; i++) {
            sum[i] = i == 0 ? nums[i] : sum[i - 1] + nums[i];
            // 先处理掉特殊情况
            if (sum[i] >= s) {
                ans = Math.min(ans, i + 1);
            }
        }
        
        // 二分查找符合条件的点
        for (int i = 0; i < nums.length; i++) {
            int target = s + sum[i];
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int mid = (right - left) / 2 + left;
                if (sum[mid] < target) {
                    left = mid + 1;
                } else {
                    ans = Math.min(ans, mid - i);
                    right = mid;
                }
            }
            if (sum[right] >= target) {
                ans = Math.min(ans, right - i);
            }
        }
        
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}
This problem can be solved using binary search. We can try to find the minimum possible maximum sum in a subarray by binary searching over the range of possible values. The upper bound of this range is the sum of all elements in the array, since each subarray must have at least one element. The lower bound of this range is the maximum element in the array, since each subarray must have at least one element and the maximum element must be in its own subarray. For each guess of the maximum sum, we can try to divide the array into subarrays such that no subarray has a sum greater than the guess. This can be done by iterating through the array and greedily assigning each element to the current subarray until the sum of the subarray is greater than the guess. Then, we start a new subarray with the current element. If we can divide the array into k subarrays with a maximum sum no greater than our guess, we can try a smaller guess. If we cannot divide the array into k subarrays with a maximum sum no greater than our guess, we need to try a larger guess. Here's some sample code in Python: ``` n, k = map(int, input().split()) arr = list(map(int, input().split())) low = max(arr) high = sum(arr) while low < high: mid = (low + high) // 2 count = 1 total = 0 for x in arr: if total + x > mid: count += 1 total = x else: total += x if count > k: low = mid + 1 else: high = mid print(low) ``` This code reads in the input and initializes the range of possible values for the maximum sum in a subarray. Then, it performs binary search to find the minimum possible maximum sum. For each guess of the maximum sum, it tries to divide the array into k subarrays such that no subarray has a sum greater than the guess. If it can do this, it tries a smaller guess. If not, it tries a larger guess. Finally, it prints out the minimum possible maximum sum.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值