LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题
Posted 人工智障专家
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题相关的知识,希望对你有一定的参考价值。
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguoussubarray 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(nlog n).
思路:使用滑动窗口,窗口右侧先向右扩张,使用一个变量sum来记录窗口中数字的总和,当sum大于s的时候,窗口左侧右移来缩小窗口并将sum减去nums[left]。重复此操作直到right到达数组的末尾,而left到达临界值。
1 public class Minimum_Size_Subarray_Sum { 2 public static int minSubArrayLen(int s, int[] nums) { 3 if(null==nums||nums.length==0){ 4 return 0; 5 } 6 7 int left = 0; 8 int minLeft = 0; 9 int minLen = nums.length; 10 int sum = 0; 11 int maxSum = Integer.MIN_VALUE; 12 13 for(int right=0;right<nums.length;right++){ 14 if(sum<s){ 15 sum += nums[right]; 16 if(sum>maxSum){ 17 maxSum = sum; 18 } 19 } 20 21 while(sum>=s){ 22 if(right-left+1<minLen){ 23 minLeft = left; 24 minLen = right - left + 1; 25 } 26 27 sum -= nums[left]; 28 left++; 29 } 30 } 31 32 if(maxSum<s){ 33 return 0; 34 } 35 36 return minLen; 37 } 38 39 public static void main(String[] args) { 40 int[] nums = {1,1,1,1,1,1}; 41 System.out.println(minSubArrayLen(6, nums)); 42 43 } 44 }
类似题目:
窗口最小子串问题 https://www.cnblogs.com/blzm742624643/p/10357757.html
以上是关于LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 209: Minimum Size Subarray Sum
leetcode 209. Minimum Size Subarray Sum
刷题-LeetCode209. Minimum Size Subarray Sum
LeetCode-209.Minimum Size Subarray Sum