Leetcode: Minimum Size Subarray Sum
2015-12-17 06:52
459 查看
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 [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).
Haven't think about the O(nlogn) solution.
O(n) solution is to maintain a window
public class Solution { public int minSubArrayLen(int s, int[] nums) { int minWin = Integer.MAX_VALUE; int l=0, r=0; if (nums==null || nums.length==0) return 0; int sum = 0; while (r < nums.length) { sum += nums[r]; while (sum >= s) { minWin = Math.min(minWin, r-l+1); sum -= nums[l++]; } r++; } if (r==nums.length && l==0 && sum<s) return 0; return minWin; } }
Initially I'm concerning I should maintain the window to have its sum always be >= s, and l should always fall at a place maintaining this property. But the solution above proves that I need not do this. Anyway, my solution also works as follows:
public class Solution { public int minSubArrayLen(int s, int[] nums) { int minWin = Integer.MAX_VALUE; int l=0, r=0; if (nums==null || nums.length==0) return 0; int sum = 0; while (r < nums.length) { sum += nums[r]; if (sum >= s) { //found one feasible window, try to shrink the window while (l<=r && sum-nums[l] >= s) { sum -= nums[l++]; } minWin = Math.min(minWin, r-l+1); } r++; } if (r==nums.length && l==0 && sum<s) return 0; return minWin; } }
相关文章推荐
- Spring,Struts2,MyBatis,Activiti,Maven,H2,Tomcat集成(一)——Maven,Tomcat,Spring集成
- Leetcode: Add and Search Word - Data structure design
- Distance between subspacess
- 10008---CSS Background背景
- 介绍几款Python IDE
- AngularJS Best Practices: resource
- 【纯感悟】我眼里的安卓架构师(一)
- 编译器对C函数的名字修饰
- ASA防火墙疑难杂症解答
- Project5&6 Verilog开发流水线CPU
- Is the type of “pointer-to-member-function” different from “pointer-to-function”?
- LeetCode "Maximum Product of Word Lengths"
- 关于大型网站技术演进的思考(二)--存储的瓶颈(2)
- C ++排序函数sort(),qsort()
- iis7设置dz论坛url静态化经验
- android自带标题样式
- 字典管理表空间 本地管理表空间 之间的区别(未懂)
- [LeetCode317]Shortest Distance from All Buildings
- [leetcode] 84. Largest Rectangle in Histogram 解题报告
- iGrimace V8 简单的安装方式