Skip to content

Latest commit

 

History

History
80 lines (64 loc) · 2.12 KB

209. Minimum Size Subarray Sum.md

File metadata and controls

80 lines (64 loc) · 2.12 KB

Difficulty : Medium

Related Topics : ArrayTwo PointersBinary Search


leetcode-cn Daily Challenge on June 28, 2020.


Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

Follow up:

  • If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

Solution

  • mine
    • Java
      • Two Pointer Runtime: 1 ms, faster than 99.93%, Memory Usage: 39.6 MB, less than 43.11% of Java online submissions
        // O(n)time 
        // O(1)space
        public int minSubArrayLen(int s, int[] nums) {
            int len = nums.length;
            int res = len + 1;
            int pre = 0, cur = 0;
            int sum = 0;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] >= s){
                    return 1;
                }
                sum += nums[i];
                cur++;
                while(sum >= s){
                    sum -= nums[pre];
                    res = Math.min(cur - pre, res);
                    pre++;
                }
            }
            return res == len + 1 ? 0 : res;
        }
        

  • the most votes
    • Two Pointer Runtime: 1 ms, faster than 99.93%, Memory Usage: 39.5 MB, less than 62.72% of Java online submissions
      // O(n)time 
      // O(1)space
      public int minSubArrayLen(int s, int[] a) {
          if (a == null || a.length == 0)
              return 0;
      
          int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
      
          while (j < a.length) {
              sum += a[j++];
              while (sum >= s) {
                  min = Math.min(min, j - i);
                  sum -= a[i++];
              }
          }
          return min == Integer.MAX_VALUE ? 0 : min;
      }