标签:
leetcode 209
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.
===========
给定一个整数数组int a[] = {2,3,1,2,4,3
},给定一个整数数字s;
求在a中子数组累加和 大于等于s中,长度最小的子数组长度;否则返回0;
一种时间复杂度o(n)的算法。
class A{ public: int minSubArrayLen(int s, vector<int>& nums) { int start = 0; int minlen = INT_MAX; int tsum = 0; for(int i = 0;i<(int)nums.size();i++){ tsum +=nums[i]; while(tsum >= s){ minlen = min(minlen,i-start+1); tsum = tsum - nums[start++];///关键是这一步,当tsum>=3是,start下标一直前进,而i下标是不变的 } } return minlen==INT_MAX? 0: minlen; } };
大于或等于给定值 长度最小的子数组 minimum size subarray sum [209]
标签:
原文地址:http://www.cnblogs.com/li-daphne/p/5550834.html