題目#
leetcode 1 - Two Sum (題目說明請點連結)
題目簡述#
在數組中找到兩個數字,使得它們的和等於給定的目標值,並返回它們的索引。
範例#
Example 1:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: 因為 nums[0] + nums[1] == 9,所以返回 [0, 1]。Example 2:
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation: 因為 nums[1] + nums[2] == 6,所以返回 [1, 2]。解題思路#
這題要求我們在數組中找到兩個數字,這兩個數字的和等於給定的 target,並返回它們的索引。這是經典的 HashMap 問題,可以利用HashMap高效地解決,時間複雜度為 O(n)。
解法#
我們可以使用HashMap來存儲每個數字的索引,當我們遍歷數組中的每一個數字時,檢查是否存在一個數字,使得 target - nums[i] 等於某個已經出現過的數字。如果存在,就直接返回這兩個數字的索引。
具體步驟如下:
- 初始化一個空的HashMap
map,用來存儲數字的值和索引。 - 遍歷數組
nums,對於每個元素nums[i],計算target - nums[i],並檢查HashMap中是否存在這個差值。 - 如果存在,則返回這兩個數字的索引。
- 如果不存在,則將當前數字及其索引放入HashMap中。
例子說明#
nums = [2, 7, 11, 15], target = 9
- 初始情況:
map = {},target = 9,我們從nums中遍歷每一個數字。
處理第一個數字
2:- 計算
target - 2 = 9 - 2 = 7。 - HashMap
map中沒有7,所以把2和它的索引0存入HashMap,map = {2: 0}。
- 計算
處理第二個數字
7:- 計算
target - 7 = 9 - 7 = 2。 - HashMap
map中有2,所以返回map.get(2)和當前索引1,即返回[0, 1]。
- 計算
所以答案是 [0, 1],表示 nums[0] + nums[1] = 9。
完整程式碼#
java
import java.util.Map;
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(); // 初始化一個HashMap來存儲數字和索引
for (int i = 0; i < nums.length; i++) { // 遍歷數組
if (map.containsKey(target - nums[i])) { // 檢查HashMap中是否存在目標數字的差值
return new int[] { map.get(target - nums[i]), i }; // 如果存在,返回索引
} else {
map.put(nums[i], i); // 如果不存在,將當前數字和索引存入HashMap
}
}
return new int[2]; // 返回空數組(理論上不會到這一步)
}
}時間複雜度#
- 時間複雜度:O(n),其中 n 是數組的長度
- 空間複雜度:O(n),用於存儲 HashMap

