【题目描述】
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 -1 instead.
给定一个由 n 个正整数组成的数组和一个正整数 s ,请找出该数组中满足其和 ≥ s 的最小长度子数组。如果无解,则返回 -1。
【题目链接】
www.lintcode.com/en/problem/minimum-size-subarray-sum/
【题目解析】
sum为前i个数的和,长度比nums多一个,sum[0] = 0。这样从0开始一直到len,遍历sum计算sum[j]与sum[i]的差大于等于s的时候的j-i长度,把它与minlen比较,如果比minlen小就更新minlen。
一开始minlen的初始化值是len + 1,如果最后minlen的值仍旧为len + 1,说明没有找到这样的minlen满足题意。则直接返回0;否则返回minlen的值
【参考答案】
网友评论