回歸次數(shù):1
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處
題目:
給定一個(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]
解答:
public class Tes {
/**
* 最簡(jiǎn)單思路,兩次遍歷
* 空間復(fù)雜度:O(n * n)
* @param nums
* @param target
* @return
*/
public int[] twoSum1(int[] nums, int target) {
for (int i = 0;i < nums.length;i ++){
for(int j = i + 1;j < nums.length;j ++){
if (nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[0];
}
/**
* 優(yōu)化,放入hashmap一次,循環(huán)數(shù)組對(duì)比的時(shí)候,O(1)
* 空間復(fù)雜度:O(n)
* @param nums
* @param target
* @return
*/
public int[] twoSum2(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0;i < nums.length;i ++){
map.put(nums[i],i);
}
for (int i = 0;i < nums.length;i ++){
int current = target - nums[i];
if (map.containsKey(current) && i != map.get(current)){
//說明存在
return new int[]{i,map.get(current)};
}
}
return new int[0];
}
/**
* 一次hashmap,直接對(duì)比
* 空間復(fù)雜度:O(n)
* 但是比上一個(gè)優(yōu)化n更優(yōu)
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0;i < nums.length;i ++){
//首先判斷需要的另外一個(gè)數(shù)
int current = target - nums[i];
if (map.containsKey(current)){
return new int[]{i,map.get(current)};
}else{
map.put(nums[i],i);
}
}
return new int[0];
}
public static void main(String[] args) {
int[] test = new int[]{1,3,4,5,6};
Tes tes = new Tes();
int[] r = tes.twoSum(test,7);
for (int i :
r) {
System.out.println(i);
}
}
}