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, and you may not use the same element twice.
1.
方法一:用hashmap映射键值对应关系
public static int[] twoSum(int[] num,int target ) {
final HashMap<Integer,Integer> myMap = new HashMap<Integer, Integer>();
//int []result = new int[2];
for (int i = 0; i < num.length; i++) {
myMap.put(num[i], i);
}
for (int i = 0; i < num.length; i++) {
final Integer v = myMap.get(target-num[i]);
if(v != null && v > i){
return new int[]{i,v};
}
}
return null;
}
方法二:两个for逐一比较
public static 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;
}