您的位置:首页 > 编程语言 > C语言/C++

Leetcode Minimum Size Subarray Sum

2015-10-24 10:15 495 查看
Leetcode Minimum Size Subarray Sum ,本算法主要通过两个游标记录求和的范围,并不断移动end游标,如果和大于s,则移动begin游标,从而缩紧约束,同时不断记录当前求和范围长度,相关cpp代码以及测试如下:

#include<iostream>
#include<vector>
#include<climits>

// The basic method fo this algorithm is that we record the begin and end index
// of some subarray, and increase the end index of the subarray each time.
// We check the sum of the subarray after we increace the end index, if the
// summary of the subarray is greater than s, we just increase the begin index
// to decrease the member of the subarray until the threshold value.
// We compare the (end - begin + 1) with current minimal length.
// Do these until end arrive the end of the nums.
using namespace std;
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
// If the array is empty, just return 0.
if (nums.size() == 0) {
return 0;
}
int begin = 0;
int end = 0;
int sum = 0;
int len = nums.size();
int min = INT_MAX;
for (; end < len; end ++) {
sum += nums[end];
// Decrease the summary to the threshold.
while (sum - nums[begin] >= s) {
sum -= nums[begin];
begin ++;
}
// Update the minimal length if necessary.
if (sum >= s && end - begin + 1 < min) {
min = end - begin + 1;
}
}
return min < INT_MAX? min: 0;
}
};

// Sample:
// input: ./a.out 7 2 3 1 2 4 3
// output: result: 2
int main(int argc, char* argv[]) {
Solution so;
vector<int> test;
for (int i = 2; i < argc; i ++) {
test.push_back(atoi(argv[i]));
}
int re = so.minSubArrayLen(atoi(argv[1]), test);
cout<<"result: "<<re<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp