[Leetcode] 209 Minimum Size Subarray Sum, leetcodesubarray
(1) O (logN) Solution
First, process the original array into the form of the forward and, so as to ensure the order of the array (note that the first is 0, push itself in), and then traverse the array, find the smallest subscript smaller than or equal to sum [I] + s. If it cannot be found, the break ends. Otherwise, continue and take the minimum value.
class Solution {public: int minSubArrayLen(int s, vector<int>& nums) { vector<int> sum; int ans=100000000,temp=0; sum.push_back(0); for(int i=0;i<nums.size();i++) { temp+=nums[i]; sum.push_back(temp); } for(int i=0;i<sum.size();i++) { int n=lower_bound(sum.begin(),sum.end(),s+sum[i])-sum.begin(); if(n==sum.size()) break; ans=min(ans,n-i); } if(ans==100000000) return 0; else return ans; }};(2) O (N) Solution
The two pointers start end and end go backward until sum is greater than s. Then start is backward until sum is less than s. The min value is updated at the same time. It is similar to a sliding window.
public class Solution { //1,1,4 public int minSubArrayLen(int s, int[] nums) { //init check int start = 0; int end = 0; int sum = 0; int min = Integer.MAX_VALUE; while(start<nums.length && end<nums.length) { while(sum<s && end<nums.length) { sum += nums[end++]; } while(sum>=s && start<=end) { min = Math.min(min, end-start); sum -= nums[start++]; } } return min==Integer.MAX_VALUE ? 0 : min; }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.