lintcode刷题——和大于S的最小子数组
来源:互联网 发布:word电脑软件 编辑:程序博客网 时间:2024/05/18 16:17
lintcode刷题之和大于s的最小子数组
原题如下:
给定一个由 n 个整数组成的数组和一个正整数 s ,请找出该数组中满足其和 ≥ s 的最小长度子数组。如果无解,则返回 -1。
给定数组 [2,3,1,2,4,3]
和 s = 7
, 子数组 [4,3]
是该条件下的最小长度子数组。
1、用两根指针,对数组进行遍历;
2、注意在判断子数组长度的时候,要用min来保证始终是最小的长度。
具体C++代码如下:
class Solution {
public:
/**
* @param nums: a vector 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 start=0,end=0;
int l=nums.size();
if(l==0)
return -1;
int sum=0;
int res=l+1;//res赋初值为数组长度加1
while(end<l)
{
sum+=nums[end];
if(sum>=s)
{
res=min(res,end-start+1);//为了保证此时的字数组长度是最小的
while(sum>=s&&start<=end)//当满足子数组之和大于等于s的时候,第二根指针发挥作用,从头开始减去子数组里面的元素
{
res=min(res,end-start+1);
sum-=nums[start];
start++;
}
}
end++;
}
if(res==l+1)
return -1;
else
return res;
}
};
- lintcode刷题——和大于S的最小子数组
- LintCode-和大于S的最小子数组
- lintcode-406-和大于S的最小子数组
- LintCode: 和大于S的最小子数组
- LintCode-和大于S的最小子数组
- lintcode(406)和大于S的最小子数组
- LintCode:M-和大于S的最小子数组
- 和大于S的最小子数组-LintCode
- lintcode--和大于s的最小数组
- 和大于S的最小子数组
- [Lintcode]Minimum Size Subarray Sum 和大于S的最小子数组
- 题目:和大于S的最小子数组
- 406. 和大于S的最小子数组
- 最小子数组—LintCode
- 406.Minimum Size Subarray Sum-和大于S的最小子数组(中等题)
- LintCode--最小子数组
- lintcode ----最小子数组
- LintCode: 最小子数组
- left join 和 left outer join 的区别
- mysql查询数据库中重复的字段的值
- 8月3日PHP学习笔记
- mysql入门(四)
- 要求可以根据每个学生的成绩进行由高到低的排序如果成绩相等则按照年龄由低到高排序数据的样式如下张三:19:90|李四:20:90|王五:20:80|赵六:21:100
- lintcode刷题——和大于S的最小子数组
- 关于C语言数量类型的转换
- [题解+|高能+]A+B Problem花样解法
- JAVA API 1.8中文版(百度版和谷歌版)免费下载
- RxSwift 实战操作【注册登录】
- 计算某年、某月、某日和某年、某月、某日之间的天数间隔。要求年、月、日通过键盘输入传递到程序中。
- Reflect in PHP(PHP中的反射机制)
- Integer类型值相等或不等分析
- 快速幂(矩阵快速幂)