給定一個(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]
第一種是冒泡查找陪每,但不能是同一個(gè)數(shù)字;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] a = new int[2];
for(int i = 0; i < nums.length; i++){
int res = target - nums[i];
for(int j = 0; j < nums.length; j++){
if(res ==nums[ j] && i != j){
a[0] = i;
a[1] = j;
return a;
}
}
}
return a;
}
}
第二種:用Hash
為了使得代碼的復(fù)雜度降低镰吵,我們可以采取第二種形式,是通過(guò)java中的hashmap 的方法檩禾,在這里無(wú)基礎(chǔ)的也將可以使用hashmap 的用法Map <Integer,Integer> map = new HashMap<>();
map.put 是將鍵值推入
map.containsKey 是找到值,
而map.get 是獲取鍵
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map <Integer,Integer> map = new HashMap<>();
for(int i = 0 ; i < nums.length; i++){
map.put(nums[i],i);
}
for(int j = 0; j < nums.length; j++){
int k = target - nums[j];
if(map.containsKey(k) && j != map.get(k)){
result[0] =j;
result[1] = map.get(k);
return result;
}
}
return result;
}
}