You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套数组循环迭代疑问:为何首循环取length-2、次循环取length-1?

Understanding the Loop Bounds in the 3-Sum Problem

Great question! Let's break this down using the classic sorted array + two-pointer approach for the 3-sum problem—this is almost certainly the solution you're referencing.

Why i stops at array.length - 2

Think about what we need for each iteration of the outer loop: the first element (at index i) needs to have at least two other elements after it to form a valid triplet (i, j, k). If we let i go all the way to array.length - 1, there are no elements left after it. If we let i reach array.length - 2, the only element left after it is array.length - 1—not enough for both j and k.

So the loop condition i < array.length - 2 ensures that i always has at least two elements following it (since j starts at i+1 and k starts at the end of the array), guaranteeing we can form a triplet every time we enter the inner logic.

Why k starts at array.length - 1

This is where the two-pointer trick shines. Since the array is sorted:

  • We start j right after i (the smallest remaining element) and k at the end (the largest remaining element).
  • If the sum of array[i] + array[j] + array[k] is less than the target, we need a larger sum—so we move j to the right.
  • If the sum is greater than the target, we need a smaller sum—so we move k to the left.
  • If it's equal to the target, we've found our triplet, and can adjust both pointers to skip duplicates (if needed) and keep searching.

Starting k at the end means we don't have to iterate through every possible element after j for each i—the sorted order lets us "jump" to the right candidates instead of checking every single combination. This cuts down on unnecessary checks while still covering all possible valid triplets.

Do we miss any valid triplets by not iterating all elements?

Absolutely not! Here's why:

  • For each i, we're checking every possible pair of elements that come after i—but in a smart way. The two-pointer movement ensures we cover every possible (j, k) pair where j > i and k > j without redundant checks.
  • Since the array is sorted, we don't need to check pairs in reverse order (like j starting at the end and k starting at i+1) because that would just be repeating the same combinations we already checked with earlier i values.

This approach is efficient because it leverages the sorted array's properties to avoid redundant work, while still ensuring we don't miss any potential triplets that add up to the target.

内容的提问来源于stack exchange,提问作者Jeremiah Mora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:53:42