大于或等于给定值 长度最小的子数组
leetcode 209
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.
===========
给定一个整数数组int a[] = {2,3,1,2,4,3
},给定一个整数数字s;
求在a中子数组累加和 大于等于s中,长度最小的子数组长度;否则返回0;
一种时间复杂度o(n)的算法。
==========
思路:两个指针的思路,
start指向目标数组的开始位置,
i指向待查找位置,
[start,i]组成了当前数组已经发现的子数组,子数组可能会随着i一直扩大,
tsum表示子数组的元素和,如果tsum>s说明发现一个解,记下现在子数组的长度[i-start+1]
===========
code:
class A{ public: int minSubArrayLen(int s, vector<int>& nums) { int start = 0; int minlen = INT_MAX; int tsum = 0; for(int i = 0;i<(int)nums.size();i++){ tsum +=nums[i]; while(tsum >= s){ minlen = min(minlen,i-start+1); tsum = tsum - nums[start++];///关键是这一步,当tsum>=3是,start下标一直前进,而i下标是不变的 } } return minlen==INT_MAX? 0: minlen; } };