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] 209. Minimum Size Subarray Sum 最短子数组之和的更多相关文章

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

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

  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 209. Minimum Size Subarray Sum (最短子数组之和)

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

  4. LeetCode 209 Minimum Size Subarray Sum

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

  5. Java for LeetCode 209 Minimum Size Subarray Sum

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

  6. 【刷题-LeetCode】209. Minimum Size Subarray Sum

    Minimum Size Subarray Sum Given an array of n positive integers and a positive integer s, find the m ...

  7. LeetCode OJ 209. Minimum Size Subarray Sum

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

  8. [LeetCode] 930. Binary Subarrays With Sum 二元子数组之和

    In an array A of 0s and 1s, how many non-empty subarrays have sum S? Example 1: Input: A = [1,0,1,0, ...

  9. 【LeetCode】209. Minimum Size Subarray Sum 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/minimum- ...

随机推荐

  1. Entity Framework Core 练习参考

    项目地址:https://gitee.com/dhclly/IceDog.EFCore 项目介绍 对 Microsoft EntityFramework Core 框架的练习测试 参考文档教程 官方文 ...

  2. visa

  3. laravel Method Illuminate\Validation\Validator::validateReuqired does not exist.

    Method Illuminate\Validation\Validator::validateReuqired does not exist. 此错误是由于我们在配置验证时,写错了关键字, publ ...

  4. CTF挑战赛丨网络内生安全试验场第一季答题赛火热开启

    前期回顾:挑战世界级“人机大战”,更有万元奖金等你来拿 网络内生安全试验场自上线以来,受到了业内的极大重视与关注. 自9月2日报名通道开启后,报名量更是持续高升,上百名精英白帽踊跃报名. 至此,网络内 ...

  5. CTF必备技能丨Linux Pwn入门教程——ShellCode

    这是一套Linux Pwn入门教程系列,作者依据i春秋Pwn入门课程中的技术分类,并结合近几年赛事中出现的一些题目和文章整理出一份相对完整的Linux Pwn教程. 课程回顾>> Linu ...

  6. 利用Injecttion优化编辑的速度,你不是缺一台性能优化的电脑而是缺一个快速编译的工具~

    请前往如下的链接查看优化编译速度: https://www.jianshu.com/p/b2a2f15a3283

  7. Docker下载镜像太慢问题

    我在linux上安装了Docker,docker pull 了一个nginx镜像,真他妈是太慢了用了1-2个小时才下载完成. 在网上找到了优化方法,那真是速度一下就起飞了,其实只要配置一下拉取的doc ...

  8. Linux 初识Libevent网络库

    初识Libevent libevent是用c写的高并发网络io库,只要有文件描述符,就都可使用libevent. libevent使用回调函数(callback) . 有了libevent,网络编程我 ...

  9. Tests in error:BlogApplicationTests.initializationError » IllegalState Unable to find a @Spri...【解决】

    刚刚写完一个项目,准备打包,却发现无法打包. 然后认真排查了一下问题.发现少引入了一个插件. <plugin> <groupId>org.apache.maven.plugin ...

  10. Linux创建高级用户并删除

    Linux创建高级用户并删除 常见window系统可以创建许多用户,但是linux也可以创建许多用户. 方法比window方便简单. (1)添加一个普通用户 :nangong(名字自己取) usera ...