LintCode:M-和大于S的最小子数组
来源:互联网 发布:我的战争预告片知乎 编辑:程序博客网 时间:2024/05/17 07:04
LintCode链接
给定一个由 n 个整数组成的数组和一个正整数 s ,请找出该数组中满足其和 ≥ s 的最小长度子数组。如果无解,则返回 -1。
样例
给定数组 [2,3,1,2,4,3]
和 s = 7
, 子数组 [4,3]
是该条件下的最小长度子数组。
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) { // write your code here return helper(nums, s); } //双指针 //TC = O(n) int helper(int[] nums, int s){ int n = nums.length; int minLen=Integer.MAX_VALUE; int start=0; int end=0; int sum=0; while(end<n){ sum+=nums[end]; if(sum>=s){ while(sum>=s && start<=end){ minLen = Math.min(minLen, end-start+1); sum-=nums[start++]; } } end++; } return minLen==Integer.MAX_VALUE?-1:minLen; } //枚举 //TC = O(n^2) //SC = O(n) int helper_enum(int[] nums, int s){ int n = nums.length; int[] sums = new int[n]; for(int i=0; i<n; i++){ if(i==0) sums[0] = nums[0]; else sums[i] = sums[i-1]+nums[i]; if(nums[i]>=s) return 1; } for(int len=2; len<=n; len++){ for(int i=0; i+len-1<n; i++){ int j=i+len-1; int tmp = sums[j]-((i==0)?0:sums[i-1]); if(tmp>=s) return len; } } return -1; }}
阅读全文
0 0
- LintCode:M-和大于S的最小子数组
- LintCode-和大于S的最小子数组
- lintcode-406-和大于S的最小子数组
- LintCode: 和大于S的最小子数组
- LintCode-和大于S的最小子数组
- lintcode(406)和大于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--最小子数组
- hdu 1398 母函数
- SSM框架整合 配置文件
- java下载乱码问题
- Openldap集成tls/ssl
- Linux下C程序的编辑,编译和运行以及调试
- LintCode:M-和大于S的最小子数组
- 浅谈gcc命令
- js前端加行
- 借助友盟提供的多渠道打包的方式,用于渠道统计
- xib关联view
- 配置openldap使用SSL连接
- mybatis中#{}和${}的区别
- 获取运行时的函数名
- Android之设计模式六大原则