給定一個整數(shù)數(shù)組和一個目標值,找出數(shù)組中和為目標值的兩個數(shù)。
你可以假設(shè)每個輸入只對應(yīng)一種答案,且同樣的元素不能被重復(fù)利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解答:一遍哈希表
在進行迭代并將元素插入到表中的同時,我們還會回過頭來檢查表中是否已經(jīng)存在當前元素所對應(yīng)的目標元素。如果它存在,那我們已經(jīng)找到了對應(yīng)解,并立即將其返回。
復(fù)雜度分析:
時間復(fù)雜度:O(n), 我們只遍歷了包含有 n 個元素的列表一次。在表中進行的每次查找只花費 O(1) 的時間。
空間復(fù)雜度:O(n), 所需的額外空間取決于哈希表中存儲的元素數(shù)量,該表最多需要存儲 n個元素。
代碼
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
if(length < 1){
return null;
}
Map<Integer, Integer> numMap = new HashMap<>();
int[] results = new int[2];
for (int i = 0; i < length; i++) {
int current = nums[i];
int key = target - current;
Integer otherIndex = numMap.get(key);
if (otherIndex != null) {
results[0] = otherIndex;
results[1] = i;
break;
}
numMap.put(current, i);
}
return results;
}