今天我要分享一個經典的程式題目 —— Two Sum。題目很簡單:
給你一個整數陣列 nums 和一個目標值 target,找出陣列中 兩個數字的索引,使它們相加等於目標值。
每個陣列只會有一個解,而且不能使用同一個元素兩次。
這個題目不僅常出現在程式面試,也非常適合作為練習 HashMap 的應用。
程式碼示範(Java)
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numToIndex.containsKey(complement)) {
return new int[] { numToIndex.get(complement), i };
}
numToIndex.put(nums[i], i);
}
return new int[] {};
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] result1 = solution.twoSum(new int[] {2,7,11,15}, 9);
System.out.println(result1[0] + "," + result1[1]); // Output: 0,1
int[] result2 = solution.twoSum(new int[] {3,2,4}, 6);
System.out.println(result2[0] + "," + result2[1]); // Output: 1,2
int[] result3 = solution.twoSum(new int[] {3,3}, 6);
System.out.println(result3[0] + "," + result3[1]); // Output: 0,1
}
}
解法說明
使用 HashMap 儲存每個數字對應的索引
每次迴圈計算 complement = target - nums[i]
如果 HashMap 裡有 complement,表示找到答案,直接返回兩個索引
否則,將當前數字加入 HashMap,繼續搜尋
這種方法時間複雜度為 O(n),比傳統兩層迴圈的 O(n²) 快很多。
心得小結
這個題目教會我兩件事:
HashMap 很好用:可以快速查找對應值,省去多層迴圈
程式思路很重要:先想「補數」再存索引,比直接兩層迴圈更直觀