題目
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)整數(shù)目標(biāo)值 target欣孤,請(qǐng)你在該數(shù)組中找出 和為目標(biāo)值 target 的那 兩個(gè) 整數(shù),并返回它們的數(shù)組下標(biāo)昔逗。
你可以假設(shè)每種輸入只會(huì)對(duì)應(yīng)一個(gè)答案降传。但是,數(shù)組中同一個(gè)元素在答案里不能重復(fù)出現(xiàn)勾怒。
你可以按任意順序返回答案婆排。
示例 1:
輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因?yàn)?nums[0] + nums[1] == 9 ,返回 [0, 1] 笔链。
示例 2:
輸入:nums = [3,2,4], target = 6
輸出:[1,2]
示例 3:
輸入:nums = [3,3], target = 6
輸出:[0,1]
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/two-sum
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有段只。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處鉴扫。
題解
- 暴力法(略)
- 哈希表
數(shù)組值為key赞枕,數(shù)組下標(biāo)為value。
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hashMap.containsKey(target - nums[i])) {
return new int[]{hashMap.get(target - nums[i]), i};
}
//hashmap中不存在對(duì)應(yīng)的key時(shí)坪创,則插入炕婶。
hashMap.put(nums[i], i);
}
return new int[0];
}