Java O(n) code using two pointers and two while


  • 0
    C

    Use two while to compute least times of length of sub-array.

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            if (nums.length == 0) return 0;
            int ans = Integer.MAX_VALUE;
            int sum = 0;
            int i = 0, j = 0;
            while (true) {
                while (sum < s && j < nums.length) {
                    sum += nums[j];
                    j++;
                }
                if (sum < s) break;
                while (sum >= s) {
                    sum -= nums[i];
                    i++;
                }
                ans = Math.min(ans, j - i + 1);
            }
            return (ans == Integer.MAX_VALUE ? 0 : ans);
        }
    }

  • 0
    C

    Maybe someone likes the following code:

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            int ans = Integer.MAX_VALUE;
            int i = 0, j = 0, sum = 0;
            
            while (j < nums.length) {
                while (sum < s && j < nums.length) {
                    sum += nums[j++];
                }
                while (sum >= s) {
                    ans = Math.min(ans, j - i);
                    sum -= nums[i++];
                }
            }
            
            return (ans == Integer.MAX_VALUE ? 0 : ans);
        }
    }

Log in to reply
 

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