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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。