嵌套数组循环迭代疑问:为何首循环取length-2、次循环取length-1?
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
jright afteri(the smallest remaining element) andkat 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 movejto the right. - If the sum is greater than the target, we need a smaller sum—so we move
kto 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 afteri—but in a smart way. The two-pointer movement ensures we cover every possible (j, k) pair wherej > iandk > jwithout redundant checks. - Since the array is sorted, we don't need to check pairs in reverse order (like
jstarting at the end andkstarting ati+1) because that would just be repeating the same combinations we already checked with earlierivalues.
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

