别人的代码
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int l, r, cum, res = nums.size()+1; l = r = cum = 0; while ((unsigned int)r < nums.size()) { cum += nums[r++]; while (cum >= s) { res = min(res, r-l); cum -= nums[l++]; } } return res<=nums.size()?res:0; } };
我的 280ms
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { vector<int> res; int start=0,end=0,len=INT_MAX; for(int end=0;end<nums.size();++end) { while(sum(nums,s,start,end) && start<=end) { (end-start+1 < len)? len=end-start+1:len; start++; } } if(len == INT_MAX) return 0; return len; } bool sum(vector<int>& nums,int s,int i,int j) { for(int k=i;k<=j;++k) s=s-nums[k]; return s<=0; } };
nlogn的解法:把数组依次相加,然后用二分查找法找到sum-nums[i].不高效,但是一个思路。
int minSubArrayLen(int s, vector<int>& nums) { vector<int> sums = accumulate(nums); int n = nums.size(), minlen = INT_MAX; for (int i = 1; i <= n; i++) { if (sums[i] >= s) { int p = upper_bound(sums, 0, i, sums[i] - s); if (p != -1) minlen = min(minlen, i - p + 1); } } return minlen == INT_MAX ? 0 : minlen; } private: vector<int> accumulate(vector<int>& nums) { int n = nums.size(); vector<int> sums(n + 1, 0); for (int i = 1; i <= n; i++) sums[i] = nums[i - 1] + sums[i - 1]; return sums; } int upper_bound(vector<int>& sums, int left, int right, int target) { int l = left, r = right; while (l < r) { int m = l + ((r - l) >> 1); if (sums[m] <= target) l = m + 1; else r = m; } return sums[r] > target ? r : -1; }