AC solution in Java


  • 0
    H

    The idea is using two pointers. Each time sum is greater than target move the slow pointer and shrink the window.

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            int n = nums.length;
            int i = 0, j = 0, sum = 0;
            int len = n+1;
            for (; i < n; i++) {
                sum += nums[i];
                while (sum >= s) {
                    if (i - j + 1 < len) {
                        len = i - j + 1;
                    }
                    sum -= nums[j++];
                }
            }
            return len == n + 1 ? 0 : len;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.