Clear O(N) Java solution


  • 1
    J

    Here is a O(N) running time Java solution that uses O(1) extra space.

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

Log in to reply
 

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