標籤:
題目連結:https://leetcode.com/problems/minimum-size-subarray-sum/
題目:
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
思路:
用兩個遊標表示當前範圍,若滿足條件則更新最小長度,否則遊標做出相應調整。
演算法:
public int minSubArrayLen(int s, int[] nums) {if (nums.length == 0)return 0;int minLen = Integer.MAX_VALUE, start = 0, end = 0;int sum = 0;while (end < nums.length) {while (sum < s && end < nums.length) {sum += nums[end++];//若不滿足 則擴大範圍}while (sum >= s && start < end) {minLen = Math.min(minLen, end - start);sum -= nums[start++];//當滿足條件後 start增大看是否還存在更小長度}}if (minLen == Integer.MAX_VALUE) {minLen = 0;}return minLen;}
【Leetcode】Minimum Size Subarray Sum