Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。
简单的算法:这个算法的复杂度为O(n∧2),思路是通过两次for循环,把第i数和第i+1到第n个数相加判定是否等于target,等于则返回它的数组下标
package leetCode;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums,int target){
Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length-1;i++){
for(int j=1;j<nums.length;j++){
if(nums[i]+nums[j]==target){ //当target等于数组的两个数组相加,就输出它的下标
return new int[] {i,j};
}
}
}
return new int[] {0,0};
}
public static void main(String[] args){
int[] a = {2,7,11,15};
int b = 9;
TwoSum t= new TwoSum();
int c[]=t.twoSum(a,b);
for(int d:c){
System.out.println(d);
}
}
}
复杂算法:算法复杂度为O(n),思路是先把数组所有数存入map并把数组的值设为key,循环的i设置为value(即把数组的下标和值交换),然后通过map.get(key)方法,用target-nums[j]=key来查找map里面是否有这个数,如果有就返回这个值的下标(在map里面是value)和nums[j]的下标。
package leetCode;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums,int target){
/*Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length-1;i++){
for(int j=1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
return new int[] {i,j};
}
}
}
return new int[] {0,0};*/
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++){
Integer index = map.get(target-nums[j]);
if(index!=null){
return new int[] {j,index};}
}
return new int[] {0,0};
}
public static void main(String[] args){
int[] a = {2,7,11,15};
int b = 17;
TwoSum t= new TwoSum();
int c[]=t.twoSum(a,b);
for(int d:c){
System.out.println(d);
}
}
}