給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target掸鹅,請(qǐng)你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù)拦赠,并返回他們的數(shù)組下標(biāo)巍沙。
你可以假設(shè)每種輸入只會(huì)對(duì)應(yīng)一個(gè)答案荷鼠。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素允乐。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
方法一:
暴力法很簡(jiǎn)單削咆,遍歷每個(gè)元素 xx蠢笋,并查找是否存在一個(gè)值與 target - xtarget?x 相等的目標(biāo)元素拨齐。
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
代碼
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2];
// 建立k-v 挺尿,一一對(duì)應(yīng)的哈希表
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
if(hash.containsKey(nums[i])){
indexs[0] = i;
indexs[1] = hash.get(nums[i]);
return indexs;
}
// 將數(shù)據(jù)存入 key為補(bǔ)數(shù) ,value為下標(biāo)
hash.put(target-nums[i],i);
}
// // 雙重循環(huán) 循環(huán)極限為(n^2-n)/2
// for(int i = 0; i < nums.length; i++){
// for(int j = nums.length - 1; j > i; j --){
// if(nums[i]+nums[j] == target){
// indexs[0] = i;
// indexs[1] = j;
// return indexs;
// }
// }
// }
return indexs;
}
}