题目描述:
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Hide Tags Array Two Pointers Binary Search
分析:
要求给定和的连续序列的最短长度,需要标记首尾的下标。因此利用双指针,从前往后,用i标记连续序列最左边的下标,j标记最右边下标。
步骤:
1.两个指针初始化为0。j每移动一步,累加nums[j],如果当前的和小于目标和,那么继续右移j;若当前和不小于目标和,则更新最小长度,然后向右移动i,直到i和j之间的序列和小于目标和为止,每移动一次i,都得更新最小长度。
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Hide Tags Array Two Pointers Binary Search
分析:
要求给定和的连续序列的最短长度,需要标记首尾的下标。因此利用双指针,从前往后,用i标记连续序列最左边的下标,j标记最右边下标。
步骤:
1.两个指针初始化为0。j每移动一步,累加nums[j],如果当前的和小于目标和,那么继续右移j;若当前和不小于目标和,则更新最小长度,然后向右移动i,直到i和j之间的序列和小于目标和为止,每移动一次i,都得更新最小长度。
以下是C++实现代码:
/*///4ms///*/
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int size = nums.size();
int minLen = size + 1; //最小长度不可能超过元素个数
if(size == 0)
return 0;
int i = 0,j = 0;
int sum = 0,len = 0;
while(j < size)
{
sum += nums[j]; //累加右指针所指元素
if(sum >= s )
{
while(sum >= s) //一直右移左指针,直到序列和小于目标值
{
len = j - i + 1;
if(len < minLen) // 更新最小序列长度
minLen = len;
sum -= nums[i]; //更新序列和
i++; //右移左指针
}
}
j++; //当前和小于目标值,则右移右指针
}
if(minLen > size) //处理不存在符合要求的序列的情况
return 0;
return minLen;
}
};