双指针
未排序正数数组中累加和为给定值的最长子数组的长度
http://www.nowcoder.com/questionTerminal/a4e34287fa1b41f9bd41f957efbd5dff
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//维护一个动态窗口;
void Print(vector<int>& nums,int k) {
if(nums.size() == 0 || k <= 0){
cout << 0 << endl;
return;
}
//定义左右边界
int left = 0;
int right = 0;
int sum = nums[left];
int len = 0;
while (left <= right ) {
if (sum == k) {
len = max(len,right - left + 1);
sum -= nums[left++];
}
else if (sum < k) {
right++;
if (right == nums.size()) {
break;
}
sum += nums[right];
}
else {
sum -= nums[left++];
}
}
cout << len << endl;
}
int main() {
int n, k;
while (cin >> n >> k) {
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
Print(nums,k);
}
return 0;
}
传音控股公司福利 332人发布