LeetCode 209. Minimum Size Subarray Sum
2016-04-09 23:52
344 查看
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
the subarray
Classical two pointers problem.
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.
Classical two pointers problem.
#include <vector> #include <iostream> #include <limits> using namespace std; int minSubArrayLen(int target, vector<int>& nums) { int minLen = nums.size() + 1; // basically any number wont reach is fine. Usually use INT_MAX int sum = 0; int i = 0, j = 0; // two pointers. One keep tracking the low scope, one tracking the high scope. while(i < nums.size()) { sum = sum + nums[i]; while(sum >= target) { minLen = min(minLen, i - j + 1); sum = sum - nums[j]; j++; } i++; } return minLen == nums.size() + 1 ? 0 : minLen; } int main(void) { vector<int> nums {7}; int len = minSubArrayLen(7, nums); cout << len << endl; }
相关文章推荐
- 使用.NET统计文件夹中文件总数
- linux中清除cache的方法
- HDU-3586 Information Disturbing(树形DP+删边)
- return能否跳出循环?终止循环。
- perf学习-linux自带性能分析工具
- perf学习-linux自带性能分析工具
- 【UFLDL-exercise6- Self-Taught Learning】
- Linux系统-目录的创建,移动或重命名和删除
- EventBus StickyEvent(粘性事件) 的应用场景! 不需要手动注销事件总线
- c++程序设计第一章 开始接触c++
- Ubuntu 14.10集成redmine和gitlab(bitnami stacks)
- 栈溢出笔记1.7 地址问题(2)
- 考拉数:求一个三位数,该三位数等与其每位数字的阶乘之和
- [BZOJ4430][Nwerc2015]Guessing Camels赌骆驼
- 设计模式之解释器模式
- Date类
- Java 反射访问私有方法和字段
- 求1! + 2! + 3! + 4! + …… + 10!的和 叹号表示阶乘,如4! = 1 * 2 * 3 * 4
- sublime-text常用快捷键
- hello