209. Minimum Size Subarray Sum
1. 题目
209. Minimum Size Subarray Sum
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).
2. 题目分析
给定n,从给定数组中找到最小数量的连续子数组的和大于等于n的子数组。其实这就是硬币找零问题的翻版。
子集问题的归纳,可以参考我的另一篇博文子集问题—78. Subsets && 90. Subsets II
3. 解题思路
因为是需要连续的子数组(则不能先排序),并且要求保证最小数量的子数组,所以可以使用两个指针left、right,滑动窗口的算法,两个指针控制窗口的大小,即子数组的数量,如果发现和小于target,则窗口往右边滑动,即right++;如果和大于等于target,则说明找到了符合条件的子集,然后再找最小子集,即从窗口左边往右边缩减,从而找到最小子集。
4. 代码实现(java)
package com.algorithm.leetcode.binarySearch;
/**
* Created by 凌 on 2019/2/9.
* 注释:209. Minimum Size Subarray Sum
*/
public class MinSubArrayLen {
public static void main(String[] args) {
int s = 7;
int[] nums = {2,3,1,2,4,3};
int result = minSubArrayLen(s,nums);
System.out.println(result);
}
/**
* 题目要求:找到连续的子数组的元素之和大于等于s,必须子数组的长度最小
* 滑动窗口,使用双指针实现窗口的大小
* @param s
* @param nums
* @return
*/
public static int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length==0){
return 0;
}
int minCount = Integer.MAX_VALUE;
int left=0;
int right=0;
int sum=0;
//必须是小于等于,因为else里面是right++,如果没有等于,那么nums[nums.length-1]这个值不会放进窗口中进行比较
while (right <= nums.length){
if (sum >= s){
minCount = Math.min(minCount,right-left);
sum -= nums[left++];
}else if (right == nums.length){//防止数组越界
break;
}else {
sum += nums[right++];
}
}
return minCount == Integer.MAX_VALUE ? 0 : minCount;
}
}