Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).  

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

这道题给定了我们一个数字,让求子数组之和大于等于给定值的最小长度,注意这里是大于等于,不是等于。跟之前那道 Maximum Subarray 有些类似,并且题目中要求实现 O(n) 和 O(nlgn) 两种解法,那么先来看 O(n) 的解法,需要定义两个指针 left 和 right,分别记录子数组的左右的边界位置,然后让 right 向右移,直到子数组和大于等于给定值或者 right 达到数组末尾,此时更新最短距离,并且将 left 像右移一位,然后再 sum 中减去移去的值,然后重复上面的步骤,直到 right 到达末尾,且 left 到达临界位置,即要么到达边界,要么再往右移动,和就会小于给定值。代码如下:

解法一

// O(n)
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if (nums.empty()) return ;
int left = , right = , sum = , len = nums.size(), res = len + ;
while (right < len) {
while (sum < s && right < len) {
sum += nums[right++];
}
while (sum >= s) {
res = min(res, right - left);
sum -= nums[left++];
}
}
return res == len + ? : res;
}
};

同样的思路,我们也可以换一种写法,参考代码如下:

解法二:

class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int res = INT_MAX, left = , sum = ;
for (int i = ; i < nums.size(); ++i) {
sum += nums[i];
while (left <= i && sum >= s) {
res = min(res, i - left + );
sum -= nums[left++];
}
}
return res == INT_MAX ? : res;
}
};

下面再来看看 O(nlgn) 的解法,这个解法要用到二分查找法,思路是,建立一个比原数组长一位的 sums 数组,其中 sums[i] 表示 nums 数组中 [0, i - 1] 的和,然后对于 sums 中每一个值 sums[i],用二分查找法找到子数组的右边界位置,使该子数组之和大于 sums[i] + s,然后更新最短长度的距离即可。代码如下:

解法三:

// O(nlgn)
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int len = nums.size(), sums[len + ] = {}, res = len + ;
for (int i = ; i < len + ; ++i) sums[i] = sums[i - ] + nums[i - ];
for (int i = ; i < len + ; ++i) {
int right = searchRight(i + , len, sums[i] + s, sums);
if (right == len + ) break;
if (res > right - i) res = right - i;
}
return res == len + ? : res;
}
int searchRight(int left, int right, int key, int sums[]) {
while (left <= right) {
int mid = (left + right) / ;
if (sums[mid] >= key) right = mid - ;
else left = mid + ;
}
return left;
}
};

我们也可以不用为二分查找法专门写一个函数,直接嵌套在 for 循环中即可,参加代码如下:

解法四:

class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int res = INT_MAX, n = nums.size();
vector<int> sums(n + , );
for (int i = ; i < n + ; ++i) sums[i] = sums[i - ] + nums[i - ];
for (int i = ; i < n; ++i) {
int left = i + , right = n, t = sums[i] + s;
while (left <= right) {
int mid = left + (right - left) / ;
if (sums[mid] < t) left = mid + ;
else right = mid - ;
}
if (left == n + ) break;
res = min(res, left - i);
}
return res == INT_MAX ? : res;
}
};

讨论:本题有一个很好的 Follow up,就是去掉所有数字是正数的限制条件,而去掉这个条件会使得累加数组不一定会是递增的了,那么就不能使用二分法,同时双指针的方法也会失效,只能另辟蹊径了。其实博主觉得同时应该去掉大于s的条件,只保留 sum=s 这个要求,因为这样就可以在建立累加数组后用 2sum 的思路,快速查找 s-sum 是否存在,如果有了大于的条件,还得继续遍历所有大于 s-sum 的值,效率提高不了多少。

Github 同步地址:

https://github.com/grandyang/leetcode/issues/209

类似题目:

Minimum Window Substring

Subarray Sum Equals K

Maximum Length of Repeated Subarray

参考资料:

https://leetcode.com/problems/minimum-size-subarray-sum/

https://leetcode.com/problems/minimum-size-subarray-sum/discuss/59090/C%2B%2B-O(n)-and-O(nlogn)

https://leetcode.com/problems/minimum-size-subarray-sum/discuss/59078/Accepted-clean-Java-O(n)-solution-(two-pointers)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Minimum Size Subarray Sum 最短子数组之和的更多相关文章

  1. [LeetCode] 209. Minimum Size Subarray Sum 最短子数组之和

    Given an array of n positive integers and a positive integer s, find the minimal length of a contigu ...

  2. Minimum Size Subarray Sum 最短子数组之和

    题意 Given an array of n positive integers and a positive integer s, find the minimal length of a suba ...

  3. [LeetCode] Minimum Size Subarray Sum 解题思路

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  4. [leetcode]523. Continuous Subarray Sum连续子数组和(为K的倍数)

    Given a list of non-negative numbers and a target integer k, write a function to check if the array ...

  5. (leetcode)Minimum Size Subarray Sum

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  6. [LintCode] Continuous Subarray Sum 连续子数组之和

    Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your cod ...

  7. lintcode :continuous subarray sum 连续子数组之和

    题目 连续子数组求和 给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大.输出答案时,请分别返回第一个数字和最后一个数字的值.(如果两个相同的答案,请返回其中任意一个) 样例 给定 [-3, ...

  8. LeetCode Minimum Size Subarray Sum (最短子序列和)

    题意:给一个序列,找出其中一个连续子序列,其和大于s但是所含元素最少.返回其长度.0代表整个序列之和均小于s. 思路:O(n)的方法容易想.就是扫一遍,当子序列和大于s时就一直删减子序列前面的一个元素 ...

  9. LeetCode—Minimum Size Subarray Sum

    题目: Given an array of n positive integers and a positive integer s, find the minimal length of a sub ...

随机推荐

  1. RPC框架实现 - 通信协议篇

    RPC(Remote Procedure Call,远程过程调用)框架是分布式服务的基石,实现RPC框架需要考虑方方面面.其对业务隐藏了底层通信过程(TCP/UDP.打包/解包.序列化/反序列化),使 ...

  2. Angularjs环境搭建

    Angularjs架构搭建      1.搭建Angularjs项目           1)在package.json中配置如下,然后 npm install下载包     {   "na ...

  3. .net 一些开源的东东

    来自网络..版权归网络所有..Antlr ----- Website: http://www.antlr.org/ Copyright: Copyright (c) - Terence Parr Li ...

  4. ASP.Net MVC——DotNetZip简单使用,解决文件压缩问题。

    准备工作: 在vs工具栏中找到NuGet 下载DotNetZip 现在就可以使用DotNetZip强大的类库了,在这里我给出一些简单的使用. public ActionResult Export() ...

  5. 多线程中的volatile和伪共享

      伪共享 false sharing,顾名思义,“伪共享”就是“其实不是共享”.那什么是“共享”?多CPU同时访问同一块内存区域就是“共享”,就会产生冲突,需要控制协议来协调访问.会引起“共享”的最 ...

  6. 利用TortoiseSVN获取最新版本的OpenCV源码

    转自: http://blog.csdn.net/vsooda/article/details/7555969 1.下载安装TortoiseSVN:http://tortoisesvn.net/dow ...

  7. 物联网框架SuperIO 2.2.9和ServerSuperIO 2.1同时更新,更适用于类似西门子s7-200发送多次数据,才能读取数据的情况

    一.解决方案 二.更新内容 1.修改IRunDevice接口,把void Send(io,bytes)改成int Send(io,bytes).2.修改网络控制器,发送数据不直接使用IO实例,改为使用 ...

  8. webpack+react+antd 单页面应用实例

    React框架已经火了好长一段时间了,再不学就out了! 对React还没有了解的同学可以看看我之前的一篇文章,可以快速简单的认识一下React.React入门最好的实例-TodoList 自己从开始 ...

  9. JavaScript数组方法reduce解析

    Array.prototype.reduce() 概述 reduce()方法是数组的一个实例方法(共有方法),可以被数组的实例对象调用.reduce() 方法接收一个函数作为累加器(accumulat ...

  10. sed的应用

    h3 { color: rgb(255, 255, 255); background-color: rgb(30,144,255); padding: 3px; margin: 10px 0px } ...