leetcode209-Minimum Size Subarray Sum(最小长度子数组和)
2016-01-25 23:15
435 查看
问题描述:
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the
For example, given the array
the subarray
问题求解:
方法一:动态滑窗解决。O(n)时间,O(1)空间。
方法二:在一的基础上简化下逻辑。其他不变。
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the
sum ≥ s.If there isn’t one, return 0 instead.
For example, given the array
[2,3,1,2,4,3]and
s = 7,
the subarray
[4,3]has the minimal length under the problem constraint.
问题求解:
方法一:动态滑窗解决。O(n)时间,O(1)空间。
class Solution { public://动态滑窗解决。O(n)时间,O(1)空间。 int minSubArrayLen(int s, vector<int>& nums) { int n=nums.size(); int cur_sum = 0;//当前的和 int min_size = INT_MAX;//子数组最小长度 int begin = 0, end = 0;//子数组起始位置 while(begin < n) { if(cur_sum<s && end<n) {//(1)如果当前窗口的数相加没有达到s,则将窗口右移 cur_sum += nums[end++]; } else if(cur_sum >= s) {//(2)如果当前窗口的数相加等于或大于s,则收缩窗口 min_size = min(min_size, end-begin);//实为(end-1)-begin+1,之前end已经多加1。 cur_sum -= nums[begin++]; } else {//(3)cur_sum < s而且end>=n,则退出循环 break; } } return (min_size==INT_MAX)?0:min_size; } };
方法二:在一的基础上简化下逻辑。其他不变。
class Solution { public://动态滑窗解决。O(n)时间,O(1)空间。 int minSubArrayLen(int s, vector<int>& nums) { int n=nums.size(); if(n == 0) return 0; int min_size=INT_MAX; int cur_sum=0; int begin=0; for(int end=0;end<n;end++) {//依次遍历 //1.更新当前窗口和 cur_sum += nums[end]; while(cur_sum >= s) {//2.如果当前和大于或等于s //(1)更新最小长度 min_size = min(min_size, end-begin+1); //(2)当前和减去窗口最前的数,并且窗口前指针后移 cur_sum -= nums[begin++]; } } return (min_size==INT_MAX)?0:min_size; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解