题目:
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.
双指针。
C++版:
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { if(nums.size() == 0) return 0; int i = 0, j = 0; int sum = 0; while(sum < s && j < nums.size()) { sum += nums[j++]; } if(j == nums.size()) { if(sum < s) return 0; else if(sum == s) return nums.size(); } int global = j - i; j--; while(i != j) { if(nums[j] > nums[i] && sum > s) { sum -= nums[i++]; if(sum >= s) if(j - i + 1 < global) global = j - i + 1; } else { if(j + 1 < nums.size()) { sum -= nums[i++]; sum += nums[++j]; if(sum >= s) if(j - i + 1 < global) global = j - i + 1; } else { break; } } } return global; } };
public class Solution { public int minSubArrayLen(int s, int[] nums) { if(nums.length == 0) return 0; int i = 0, j = 0, sum = 0, result = nums.length + 1; while(j < nums.length) { while(j < nums.length && sum < s) { sum += nums[j++]; } while(sum >= s && i < j) { result = Math.min(result, j - i); sum -= nums[i++]; } } return result == nums.length + 1? 0 : result; } }
class Solution: # @param {integer} s # @param {integer[]} nums # @return {integer} def minSubArrayLen(self, s, nums): i, j, sum, result = 0, 0, 0, len(nums) + 1 if len(nums) == 0: return 0 while j < len(nums): while j < len(nums) and sum < s: sum += nums[j] j += 1 while i < j and sum >= s: result = min(result, j - i) sum -= nums[i] i += 1 return result if result != len(nums) + 1 else 0