funcslidingWindow(nums []int, k int)int { left := 0 count := 0// 或使用map记录窗口内元素 result := 0 for right := 0; right < len(nums); right++ { // 右指针扩张,更新窗口状态 count = updateCount(count, nums[right], +1) // 收缩窗口条件 for windowNeedShrink(left, right, count, k) { // 左指针收缩,更新窗口状态 count = updateCount(count, nums[left], -1) left++ } // 更新结果(注意边界处理) if windowValid(left, right, count, k) { result = updateResult(result, left, right) } } return result }
2. 双指针通用模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
functwoPointers(nums []int, target int)int { left, right := 0, len(nums)-1 result := 0 for left < right { sum := nums[left] + nums[right] if sum == target { // 找到解 result = updateResult(result, left, right) left++ // 或 right-- 根据具体情况 } elseif sum < target { left++ } else { right-- } } return result }
三、常见题型分类
1. 固定长度窗口
特点:窗口大小固定
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 示例:大小为k的子数组最大和 funcfixedWindow(nums []int, k int)int { sum := 0 for i := 0; i < k; i++ { sum += nums[i] } maxSum := sum for i := k; i < len(nums); i++ { sum = sum - nums[i-k] + nums[i] maxSum = max(maxSum, sum) } return maxSum }