LintCode-和大于S的最小子数组
来源:互联网 发布:服装设计cad软件 编辑:程序博客网 时间:2024/05/29 08:35
给定一个由 n 个整数组成的数组和一个正整数 s ,请找出该数组中满足其和 ≥ s 的最小长度子数组。如果无解,则返回 -1。
样例
给定数组 [2,3,1,2,4,3]
和 s = 7
, 子数组 [4,3]
是该条件下的最小长度子数组。
思路:数组的题一般思路大概是用两个指针扫描,这里是用一前一后两个指针都从左往右移,前面的指针一直移直到和大于s
为止;后面的指针此时一直右移,直到距离最短为止。最后返回最小子数组的大小,也就是最小子数组中元素个数。
代码如下:
public class Solution { /** * @param nums: an array of integers * @param s: an integer * @return: an integer representing the minimum size of subarray */ public int minimumSize(int[] nums, int s) { if(nums == null || nums.length == 0) return -1; int end =0; int start = 0; int sum = 0; int res = Integer.MAX_VALUE; while(end < nums.length){ sum +=nums[end]; if(sum >= s){ res = Math.min(res,end-start+1); //当扫描到数组和大于s时,从第一个元素逐次缩小数组大小, //直到符合条件的最小子数组 while(sum >= s && start <= end){ res = Math.min(res,end-start+1); sum-=nums[start]; start++; } } end++; //当前子数组的和还小于s,end往后移 } if(res == Integer.MAX_VALUE ){ //需要考虑溢出问题 return -1; } return res; }}
0 0
- 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的最小子数组
- lintcode刷题——和大于S的最小子数组
- 题目:和大于S的最小子数组
- 406. 和大于S的最小子数组
- 406.Minimum Size Subarray Sum-和大于S的最小子数组(中等题)
- LintCode--最小子数组
- lintcode ----最小子数组
- LintCode: 最小子数组
- lintcode--最小子数组
- POJ2318 TOYS
- [React Native]react-native-scrollable-tab-view(进阶篇)
- 算法(第4版):BinarySearch的运行
- 泛型
- win7下搭载ubuntu双系统,独立引导
- LintCode-和大于S的最小子数组
- 264. Ugly Number II
- POJ 4104:单词翻转
- codeforces621E————Wet Shark and Blocks(动态规划,矩阵快速幂)
- XSL和XSLT
- directshow了解
- 新一代的java模板引擎--beetl
- Java基础比较实用的总结
- IDE、编译器、编辑器