題目內(nèi)容
給定一個整數(shù)數(shù)組 nums 和一個整數(shù)目標(biāo)值 target,請你在該數(shù)組中找出 和為目標(biāo)值 的那 兩個 整數(shù),并返回它們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素不能使用兩遍。
你可以按任意順序返回答案。
【示例】
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
題解
1.雙重循環(huán)法,時間復(fù)雜度O(n^2),空間復(fù)雜度O(1)
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[i]+nums[j] == target){
return new int[]{i,j};
}
}
}
return null;
}
}
2.雙循環(huán)哈希法,時間復(fù)雜度O(n),空間復(fù)雜度O(n)
class Solution {
public int[] twoSum(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 needNum = target - nums[i];
if(map.containsKey(needNum) && i != map.get(needNum)){
if(i < map.get(needNum)){
return new int[]{i,map.get(needNum)};
}else{
return new int[]{map.get(needNum),i};
}
}
}
return null;
}
}
3.單循環(huán)哈希法,時間復(fù)雜度O(n),空間復(fù)雜度O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap();
for (int i=0;i<nums.length;i++){
int needNum = target - nums[i];
if(map.containsKey(needNum)){
if(i < map.get(needNum)){
return new int[]{i,map.get(needNum)};
}else{
return new int[]{map.get(needNum),i};
}
}
map.put(nums[i],i);
}
return null;
}
}