Leetcode 209. Minimum Size Subarray Sum
来源:互联网 发布:java ee api 编辑:程序博客网 时间:2024/06/05 00:57
209. Minimum Size Subarray Sum
Total Accepted: 54178 Total Submissions: 193578 Difficulty: MediumGiven 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 [2,3,1,2,4,3]
and s = 7
,
the subarray [4,3]
has the minimal length under the problem constraint.
click to show more practice.
More practice:
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.
Hide Similar Problems
思路:
双指针。初始化时候要判断一下首元素是不是满足。
之后右边先扩充至sum>=s,然后左边收缩至刚好不能收缩的位置。
然后更新结果。下一轮右边新加入一个元素左边继续收缩。
public class Solution { // 1ms public int minSubArrayLen(int s, int[] nums) { if(nums == null || nums.length ==0) return 0; int left = 0; int right = 1; int sum = nums[0]; if(sum >= s) return 1; int res = Integer.MAX_VALUE; while(right < nums.length){ sum += nums[right]; if(sum >= s){ while(sum - nums[left] >= s){ sum -= nums[left]; left++; } res = Math.min(res, right - left + 1); } right++; } return res == Integer.MAX_VALUE ? 0 : res; }}
O(nlogn)解法,来自讨论区
public class Solution { // 5ms public int minSubArrayLen(int s, int[] nums) { int[] cs = new int[nums.length]; // cumulative sum for (int i=0, sum=0; i<nums.length; ++i) { sum += nums[i]; cs[i] = sum; } int minLength = nums.length*2; for (int from=-1; from<nums.length-1; ++from) { int cumuSum = (from==-1 ? 0 : cs[from]) + s; int result = Arrays.binarySearch(cs, cumuSum); // actual index or should-be index int to = result<0 ? -result-1 : result; if (to < cs.length) { minLength = Math.min(minLength, to-from); } } return minLength==nums.length*2 ? 0 : minLength; }}
0 0
- [leetcode] 209.Minimum Size Subarray Sum
- 【leetcode】209. Minimum Size Subarray Sum
- <LeetCode OJ> 209. Minimum Size Subarray Sum
- [Leetcode]209. Minimum Size Subarray Sum
- [LeetCode]209. Minimum Size Subarray Sum
- leetcode 209. Minimum Size Subarray Sum
- 209. Minimum Size Subarray Sum LeetCode
- LeetCode 209. Minimum Size Subarray Sum
- LeetCode *** 209. Minimum Size Subarray Sum
- 【leetcode】209. Minimum Size Subarray Sum
- LeetCode 209. Minimum Size Subarray Sum
- leetcode.209. Minimum Size Subarray Sum
- 【LeetCode】209. Minimum Size Subarray Sum
- [Leetcode]209. Minimum Size Subarray Sum
- [leetcode]209. Minimum Size Subarray Sum[存疑]
- [leetcode] 209. Minimum Size Subarray Sum
- leetcode 209. Minimum Size Subarray Sum
- leetcode 209. Minimum Size Subarray Sum
- c++在用set和multiset时遇到的一个bug
- C语言字符串拼接
- JAVA进阶5.15——记事本界面
- 改进的Python贴吧爬虫代码
- 人民币入篮SDR:全球购买力隐形大山开始崩塌
- Leetcode 209. Minimum Size Subarray Sum
- 单链表逆序
- hdu2955 01背包 状态转化
- HDOJ 5512 Pagodas 【2015沈阳现场赛】数论
- NOJ 1002归并排序
- 微信公众平台开发----接入微信接口
- PackageManager
- TensorFlow介绍_中文版
- 字母+数字验证码(一)