题目:
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
翻译:
给定一个整数数组,返回两个数字的索引,使它们加起来等于一个特定的目标。
您可以假设每个输入都只有一个解决方案,并且不能两次使用相同的元素
方法一:使用集合,一次遍历达到目标;创建一个HashMap集合(key为数组的值value为对应数组角标),在遍历数组的过程中,我们判断target-nums[i] 的差值是否是map中元素的key值,如果是那么说明找到两个数相加为target的值,如果没有找到那么就将数组的值和角标压入集合中;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){ //判断key值中是否包含两者差值
int [] res=new int [2];
res[1]=i;
res[0]=map.get(target-nums[i]);//通过key得到value;
return res;
}
map.put(nums[i],i); //将数组元素和角标压入集合中;
}
return new int [2];
}
}
方法二:暴力法
进行双层for循环,将数组中每一个值与其它值相加进行组合;
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0 ;i<nums.length-1 ; i++){
//注意角标,i没有必要到最后一个角标,因为需要的是两个数相加的值
for(int j= i+1 ;j < nums.length ;j++){
if(target==nums[i]+nums[j])
return new int [] {i,j};
}
}
return new int [2];
}
}