150强访谈简单

二和二

“Two Sum II”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个已按非递减顺序排序的 1 索引整数数组 numbers,找到两个数字,使它们相加为特定的 target 数字。

返回两个数字 index1index2 的索引,并加一作为长度为 2 的整数数组 [index1, index2]

您不能两次使用相同的元素。您的解决方案必须仅使用恒定的额外空间。

编写一个函数 twoSum(numbers: List[int], target: int) -> List[int]

约束条件
  • 2 <= len(numbers) <= 3 * 10^4
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order
  • -1000 <= target <= 1000
  • Exactly one solution exists

示例

Example 1
Input
numbers = [2, 7, 11, 15], target = 9
Output
[1, 2]
Explanation

2 + 7 = 9. The indices are 1 and 2 (1-indexed).

Example 2
Input
numbers = [2, 3, 4], target = 6
Output
[1, 3]
Explanation

2 + 4 = 6. The indices are 1 and 3 (1-indexed).

Example 3
Input
numbers = [-1, 0], target = -1
Output
[1, 2]
Explanation

-1 + 0 = -1. The indices are 1 and 2 (1-indexed).

Need a Hint?
考虑使用特定于两指针的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。