Two Sum 解題教學:3 種解法完整比較|LeetCode 1 Best Practice

Two Sum 解題教學示意圖|LeetCode 3

本文完整拆解 LeetCode 3 Two Sum 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Two Sum 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Python

				
					from typing import List

# brute force
# time complexity: O(n^2)
# space complexity: O(1)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[j] == target - nums[i]:
                    return [i, j]

# hashMap
# time complexity: O(n)
# space complexity: O(1)

class Solution(object):
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        numMap = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in numMap:
                return [numMap[complement], i]
            numMap[num] = i
        return []


# two pointer
# time complexity: O(n)
# space complexity: O(1)

class Solution(object):
   def twoSum(self, nums: List[int], target: int) -> List[List[int]]:
       res = []
       left, right = 0, len(nums) - 1
       while (left < right):
           currSum = nums[left] + nums[right]
           if currSum < target or (left > 0 and nums[left] == nums[left - 1]):
               left += 1
           elif currSum > target or (right < len(nums)-1 and nums[right] == nums[right + 1]):
               right -= 1
           else:
               res.append([nums[left], nums[right]])
               left += 1
               right -= 1
       return res


nums = [2, 7, 11, 15]
target = 9

solution = Solution()
result = solution.twoSum(nums, target)

print(result)

				
			

Two Sum 解題思路

這題的關鍵轉念是:與其問「哪兩個數加起來等於 target」,不如邊走邊問「我現在需要的那個補數出現過了嗎」。把走過的數字連同索引存進雜湊表,每到一個新數字只要查一次 target 減掉它的差值,就能把兩層迴圈壓成一次掃描。

Two Sum 演算法步驟

  1. 建立一個雜湊表,鍵是數值、值是該數值出現的索引。
  2. 由左到右走訪陣列,對每個 nums[i] 先計算補數 complement = target – nums[i]。
  3. 若補數已存在於雜湊表,直接回傳 [雜湊表中的索引, i]。
  4. 若不存在,再把 nums[i] 與 i 寫入雜湊表,確保同一個元素不會被自己配對。

Two Sum 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(n)

每個元素只被走訪一次,雜湊表的查詢與寫入平均都是 O(1),所以整體時間是 O(n)。最壞情況下雜湊表會存下全部 n 個元素,空間因此是 O(n)——這是一個典型的用空間換時間。

Two Sum 的邊界情況與常見錯誤

  • 先查補數再寫入,順序顛倒會讓元素與自己配對(例如 target 是某元素的兩倍時)。
  • 題目保證恰有一組答案,但實作上仍建議在找不到時回傳空陣列而非未定義值。
  • 陣列中可能有重複數字,雜湊表後寫入的索引會覆蓋前者,對本題不影響正確性。
  • 負數與 0 都是合法輸入,不要假設全為正數。

Two Sum 其他解法比較

解法時間空間說明
暴力雙層迴圈O(n²)O(1)寫法最短,但資料量大會超時
先排序再雙指針O(n log n)O(n)排序後索引會亂掉,需要額外保存原始位置
一次掃描 + 雜湊表O(n)O(n)本文採用,最佳解