Minimum Size Subarray Sum
Total Accepted: 10318 Total Submissions: 44504My Submissions
Question Solution
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Hide Tags
Array Two Pointers Binary Search
Hide Similar Problems
Have you met this question in a real interview?
Yes
No
这道题采用的是两个指针(滑动窗口的方法),先从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; }
时间: 2024-10-24 13:13:11