Topic link

The problem mentioned “continuous subarrays”, first consider using the two-pointer technique to solve the problem. There are several specific forms of double Pointers

  1. Two “Pointers” move from left to right of the sequence
  2. Two “Pointers” move from right to left of the sequence. rare
  3. Two “Pointers” move from the left and right end of the sequence to the middle
  4. Two “Pointers” move from the middle of the sequence toward each end. rare

Find the smallest contiguous subarray whose elements are all positive integers and whose length is greater than or equal to target. Here we can use the sliding serial technique (a special form of # 1 above).

The specific code is as follows (submitted and approved)

import "math"

func minSubArrayLen(target int, nums []int) int {
    var (
        i int
        j int
        sum int
        // Set a maximum value to simplify the first update of minLen in the for loop.
        minLen = math.MaxInt32
        l = len(nums)
    )
    for j < l {
        // Enlarge the window
        sum += nums[j]
        j++
        // If target and are reached, the loop continues until the condition is not satisfied.
        for sum >= target {
            // Update the minimum length of the contiguous subarray that meets the condition
            if j-i < minLen {
                minLen = j-i
            }
            // Zoom out
            sum -= nums[i]
            i++
        }
        // I == j
    }
    if minLen == math.MaxInt32 {
        return 0
    }
    return minLen
}
Copy the code