⚡Flashcard Drill➔
NeetCode #199LC-167MediumTwo PointersNC 150NC 250
← Back to All Problems

#199 · #167 · Two Sum II - Input Array Is Sorted(两数之和 II - 输入有序数组)

📌 Problem Statement & Constraints

Given a 1-indexed array of integers numbers sorted in non-decreasing order, find two numbers that add up to a target and return their 1-indexed positions. Exactly one solution exists and you may not use the same element twice. Constraints: 2 <= numbers.length <= 3 * 10^4, -1000 <= numbers[i] <= 1000, -1000 <= target <= 1000.

💡 Core Algorithmic Approaches

  1. The sortedness is the key resource: with two pointers at the ends, the sum tells you which pointer to move.
  2. If the current sum is too small, the only way to increase it is to move the left pointer right.
  3. If the sum is too large, move the right pointer left.
  4. This is O(n) time with O(1) space -- better than the hash-map solution, which is O(n) space.

💻 Benchmark Python3 Implementation

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i, j = 0, len(numbers) - 1
        while i < j:
            s = numbers[i] + numbers[j]
            if s == target:
                return [i + 1, j + 1]      # 1-indexed output
            if s < target:
                i += 1                     # need a larger sum
            else:
                j -= 1                     # need a smaller sum
        return []

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each pointer moves at most n steps, so the total is O(n).
💾 Space Complexity
O(1): two indices.

⚠️ Interview Pitfalls & Follow-ups

  • Returning 0-indexed positions: the problem is explicitly 1-indexed, so +1 is required.
  • Using a hash map: correct and O(n) time, but O(n) space. The sorted input makes the two-pointer approach strictly better.
  • Moving both pointers on a mismatch: only one should move, otherwise the invariant is broken.
  • Assuming the array is strictly increasing: the problem says non-decreasing, so duplicates are possible -- but the two-pointer logic handles them fine.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

两数之和 II - 输入有序数组

给你一个下标从 1 开始的整数数组 numbers,该数组已按 非递减顺序 排列,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 ≤ index1 &lt; index2 ≤ numbers.length 。请以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标。你可以假设每个输入 只对应唯一的答案 ,而且你不可以重复使用相同的元素。约束:2 ≤ numbers.length ≤ 3 × 10^4;-1000 ≤ numbers[i] ≤ 1000;numbers 按非递减顺序排列;-1000 ≤ target ≤ 1000。

核心要点

  • 相向双指针(标准解) :l 指向最小值、r 指向最大值。若 numbers[l] + numbers[r] &lt; target ,说明需要更大的和,因此 l += 1 ;反之 r -= 1 。
  • 为什么这样不会漏解 :当和过小时, numbers[l] 与任何 ≤ numbers[r] 的元素之和都过小,因此 numbers[l] 可以安全排除;和过大时同理排除 numbers[r] 。
  • 与 1 题(两数之和)的对比 :无序数组必须用哈希表(O(n) 空间);本题 已排序 ,双指针可做到 O(1) 额外空间,是更优的解法。
  • 下标从 1 开始 :返回值需 l + 1 、 r + 1 。

常见陷阱

  • 忘记下标从 1 开始 :返回 [l, r] 会得到从 0 开始的下标,判题失败。
  • 用哈希表而不利用有序性 :虽然能过,但浪费了题目给出的「已排序」条件,空间从 O(1) 变成 O(n)。
  • 返回数值而非下标 :题目明确要求返回 下标 。
  • 指针移动方向写反 :和过小时应增大,即 l += 1 (因为数组升序,右移会取到更大的值)。

参考实现

class Solution:
    def twoSum(self, numbers: list[int], target: int) -> list[int]:
        l, r = 0, len(numbers) - 1
        while l < r:
            s = numbers[l] + numbers[r]
            if s == target:
                return [l + 1, r + 1]      # 题目要求下标从 1 开始
            if s < target:
                l += 1                     # 和过小,需要更大 -> 左指针右移
            else:
                r -= 1                     # 和过大,需要更小 -> 右指针左移
        return []