博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
209. Minimum Size Subarray Sum
阅读量:6940 次
发布时间:2019-06-27

本文共 1286 字,大约阅读时间需要 4 分钟。

Given an array of n positive integers and a positive integer s, find
the minimal length of a contiguous subarray of which the sum ≥ s. If
there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray

[4,3] has the minimal length under the problem constraint.

解法 BF

思路

暴力解法, 以数组内每一个数为起点, 知道达到s的最小个数.

复杂度

时间O(n^2) 空间O(1)

代码

class Solution {    public int minSubArrayLen(int s, int[] nums) {        int res = Integer.MAX_VALUE;        for (int i = 0; i < nums.length; i++) {            int sum = 0;            for (int j = i; j < nums.length; j++) {                sum+= nums[j];                if (sum >= s) {                    res = Math.min(j -i + 1, res);                    break;                }            }        }        return (res == Integer.MAX_VALUE)? 0:res;    }}

解法 双指针

思路

用两个指针来形成一个窗口, 使得窗口的数相加小于s. 如果加和大于s, 则将左边指针右移动, 如果指针小于s, 右边指针左移. 这里要注意的是右边指针可以到达最右边(坐标是数组唱的), 这样才能使左边指针右移找到最优解. 当左右指针相等时候就涵盖了只有一个数的corner case

注意

判定条件是left <= right &&right <= nums.length

复杂度

时间O(n) 空间O(1)

代码

class Solution {    public int minSubArrayLen(int s, int[] nums) {        int left = 0, right = 0, sum = 0, res = Integer.MAX_VALUE;        while (left <=right && right <= nums.length) {            if (sum < s) {                if (right 

转载地址:http://oksnl.baihongyu.com/

你可能感兴趣的文章
CSharp设计模式读书笔记(4):单例模式(学习难度:★☆☆☆☆,使用频率:★★★★☆)...
查看>>
PostgreSQL远端访问
查看>>
家庭里如何搭建一个互联网可访问的服务器
查看>>
eclipse与SVN 结合(删除SVN中已经上传的问题)
查看>>
webBrowser 模拟登录
查看>>
t4 template multi file output
查看>>
深入理解Fsync
查看>>
剑道基础 - 冈宪次郎
查看>>
Leading and Trailing(数论/n^k的前三位)题解
查看>>
我的php笔记(一)
查看>>
vue.js学习之better-scroll封装的轮播图初始化失败
查看>>
去掉xcode编译warning:ld: warning: directory not found for option '-L
查看>>
杭电1702--ACboy needs your help again!
查看>>
web前端开发分享-css,js进阶篇
查看>>
安大校赛/异或运算一题。
查看>>
ANT build.xml文件详解
查看>>
MVC和观察者模式
查看>>
python 基本的序列和映射规则
查看>>
强制回收和IDisposable.Dispose方法
查看>>
mybatis plus条件构造器
查看>>