↓ 跳过正文
  1. Posts/

leetcode 209. Minimum Size Subarray Sum (尺取法)

·248 字·1 分钟

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.

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

思路:尺取即可。。好久没写,竟然调了半天。。。

代码实现
 1/* ***********************************************
 2Author :111qqz
 3Created Time :2017年04月13日 星期四 20时48分00秒
 4File Name :209.cpp
 5************************************************ */
 6class Solution {
 7
 8public:
 9
10	int ruler(vector<int>nums,int tar,int n)
11	{
12	    int head = 0;
13	    int tail = 0;
14	    int sum = 0 ;
15	    int res = 0x3f3f3f3f;
16	    while (tail<n&&head<=tail)
17	    {
18		sum = sum + nums[tail];
19		if (sum>=tar)
20		{
21		    res = min(res,tail-head+1);
22		    while (sum>=tar&&head<tail)
23		    {
24			sum-=nums[head];
25			head++;
26		    }
27		    if (sum>=tar)
28		    {
29			res = min(res,tail-head+1);
30		    }
31		    else
32		    {
33			head--;
34			sum+=nums[head];
35			res = min(res,tail-head+1);
36		    }
37		}
38
39
40
41		tail++;
42	    }
43	    return res==0x3f3f3f3f?0:res;
44	}
45
46
47    int minSubArrayLen(int s, vector<int>& nums) {
48	int n = nums.size();
49	int res = ruler(nums,s,n);
50	return res;
51
52
53    }
54
55};

相关文章

leetcode 75. Sort Colors

·628 字·2 分钟
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

leetcode 11. Container With Most Water (two pointer)

·328 字·1 分钟
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.