码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_209题——Minimum Size Subarray Sum(两个指针)

时间:2015-07-19 21:29:27      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

Minimum Size Subarray Sum

 Total Accepted: 10318 Total Submissions: 44504My Submissions

 

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.

click to show more practice.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

Hide Similar Problems
 (H) Minimum Window Substring
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

 

      这道题采用的是两个指针(滑动窗口的方法),先从0开始找到一个窗口,然后通过这两个指针来移动窗口和改变窗口的大小,再保存一个最小值。一直到最后。

#include<iostream>
#include<vector>
using namespace std;


int minSubArrayLen(int s, vector<int>& nums) {
	int n=nums.size();
	int start=0;
	int end=0;
	int min;
	int sum=0;
	while(end<n)
	{
		sum+=nums[end];
		if(sum>=s)
		{
			min=end+1;
			break;
		}
		end++;
	}
	if(end>=n)
		return 0;
	while(end<n)
	{
		if(sum>=s)
		{
			while(start<=end)
			{
				sum-=nums[start];
				start++;
				if(sum>=s)
				{
					int a=end-start+1;
					if(a<min)
						min=a;
				}
				else
					break;
			}
			if(end<n&&start<end)
			{
				end++;
				sum+=nums[end];
			}
			else
				break;
		}
		else
		{
			end++;
			if(end>n)
				break;
			else
				sum+=nums[end];
		}
	}
	return min;
}



int main()
{
	int a[6]={2,3,1,2,4,3};
	vector<int> vec(a,a+6);
	cout<<minSubArrayLen(7,vec)<<endl;
}

  

leetcode_209题——Minimum Size Subarray Sum(两个指针)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4659384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!