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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- CPP 虚函数、虚函数表及虚拟继承(转)
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解