LeetCode Minimum Size Subarray Sum
2015-11-12 23:03
387 查看
Description:
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
the subarray
Solution:
Two pointers
Very similar to sliding window.
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.
Solution:
Two pointers
Very similar to sliding window.
import java.io.*; import java.util.*; /* * To execute Java, please define "static void main" on a class * named Solution. * * If you need more classes, simply define them inline. */ class Solution { public int minSubArrayLen(int s, int[] nums) { if(nums==null) return 0; int length = nums.length; int min = length+1; int left = 0, right = 0; int sum = 0; while(right<length){ if(sum+nums[right]<s){ sum+= nums[right]; right++; } else { min = Math.min(min, right-left+1); sum -= nums[left]; left++; } } if (min==length+1) return 0; return min; } }
相关文章推荐
- 好博客要记录:JVM基础概念总结:数据类型、堆与栈、基本类型与引用类型
- VC对话框坐标单位DLU和像素的转换
- 好博客要记录:JVM分代垃圾回收策略的基础概念
- 自我实现ArrayList
- 自我实现HashMap
- 单数组实现双向链表和内存管理(资源池)
- 网络协议引子 TCP/IP
- Android Fragment 真正的完全解析
- java中的构造器初始化
- 蓝懿ios 技术内容交流和学习心得 11.12
- oracle 增加列
- sql server 执行大批量的update一张表到另一张表
- 【Server 之 三】高性能的消息队列
- iptables
- oracle修改表已存列的数据类型与列名重命名
- [Android L]SEAndroid增强Androd安全性背景概要及带来的影响
- 大数阶乘
- 如何创建顺序表以及对标的一些操作
- sort uniq 取交集并集
- Android项目快速开发框架AndBase详解