链接:LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:同向双指针
九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
class Solution {
public:
/**
* @param nums: an array of integers
* @param s: An integer
* @return: an integer representing the minimum size of subarray
*/
int minimumSize(vector<int> &nums, int s) {
// write your code here
int j = 0;
int sum = 0;
int len = INT_MAX;
for (int i = 0; i < nums.size(); ++i) {
while (j < nums.size() && sum < s) {
sum += nums[j];
++j;
}
if (sum >= s) {
len = min(len, j-i);
}
sum -= nums[i];
}
return len == INT_MAX ? -1 : len;
}
};