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.
Given the array [2,3,1,2,4,3]
and s = 7
, the subarray[4,3]
has the minimal length under the problem constraint.
我自己的解法,稍嫌啰嗦
class Solution {
public:
/**
* @param nums: a vector of integers
* @param s: an integer
* @return: an integer representing the minimum size of subarray
*/
int minimumSize(vector<int> &nums, int s) {
// write your code here
if (nums.size() == 0)
return -1;
int minLen = INT_MAX;
int curSum = nums[0];
int leftPos = 0;
int rightPos = 0;
while (leftPos < nums.size())
{
if (curSum >= s)
{
if (rightPos-leftPos+1 < minLen)
{
minLen = rightPos-leftPos+1;
}
if (leftPos == rightPos)
{
if (leftPos == nums.size())
{
break;
}
else
{
leftPos++;
rightPos++;
curSum = nums[leftPos];
}
}
else
{
curSum -= nums[leftPos];
leftPos++;
}
}
else
{
if (rightPos < nums.size()-1)
{
curSum += nums[++rightPos];
}
else
break;
}
}
if (minLen == INT_MAX)
return -1;
return minLen;
}
};
其他精妙的解法
主页
课程
讲座
问答
面经
LeetCode答案
FAQ
主页
课程
讲座
问答
学员故事
面试题目
面经分享
LeetCode答案
LintCode答案
FAQ
minimum-size-subarray-sum
当前位置
首页
LeetCode 答案查询 / LintCode 答案查询
查看详情
http://www.lintcode.com/problem/minimum-size-subarray-sum/
Java
/**
* 本代码由九章算法编辑提供。没有版权欢迎转发。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
* - 更多详情请见官方网站:http://www.jiuzhang.com/
*/
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
int j = 0, i = 0;
int sum =0;
int ans = Integer.MAX_VALUE;
for(i = 0; i < nums.length; i++) { //这里的巧妙是用for循环的i作为左边的边界
while(j < nums.length && sum < s ) { //用j作为右边的边界
sum += nums[j]; //并且尽量让j向右移动
j ++;
}
if(sum >=s)
ans = Math.min(ans, j - i );
sum -= nums[i];
}
if(ans == Integer.MAX_VALUE)
ans = -1;
return ans;
}
}
© Jiu Zhang 2013-2015. All rights reserved.