Leetcode 209. Minimum Size Subarray Sum

来源:互联网 发布:java ee api 编辑:程序博客网 时间:2024/06/05 00:57

209. Minimum Size Subarray Sum

Total Accepted: 54178 Total Submissions: 193578 Difficulty: Medium

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).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Hide Company Tags
 Facebook
Hide Tags
 Array Two Pointers Binary Search
Hide Similar Problems
 (H) Minimum Window Substring (M) Maximum Size Subarray Sum Equals k

思路:

双指针。初始化时候要判断一下首元素是不是满足。

之后右边先扩充至sum>=s,然后左边收缩至刚好不能收缩的位置。

然后更新结果。下一轮右边新加入一个元素左边继续收缩。

public class Solution { // 1ms    public int minSubArrayLen(int s, int[] nums) {        if(nums == null || nums.length ==0) return 0;                int left = 0;        int right = 1;        int sum = nums[0]; if(sum >= s) return 1;        int res = Integer.MAX_VALUE;                while(right < nums.length){            sum += nums[right];             if(sum >= s){                while(sum - nums[left] >= s){                    sum -= nums[left];                    left++;                }                res = Math.min(res, right - left + 1);            }            right++;        }        return res == Integer.MAX_VALUE ? 0 : res;    }}

O(nlogn)解法,来自讨论区

public class Solution { // 5ms    public int minSubArrayLen(int s, int[] nums) {        int[] cs = new int[nums.length];  // cumulative sum        for (int i=0, sum=0; i<nums.length; ++i) {            sum += nums[i];            cs[i] = sum;        }        int minLength = nums.length*2;        for (int from=-1; from<nums.length-1; ++from) {            int cumuSum = (from==-1 ? 0 : cs[from]) + s;            int result = Arrays.binarySearch(cs, cumuSum);  // actual index or should-be index            int to = result<0 ? -result-1 : result;            if (to < cs.length) { minLength = Math.min(minLength, to-from); }        }        return minLength==nums.length*2 ? 0 : minLength;    }}


0 0