Question: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.
解法一——时间复杂度O(N2),空间复杂度O(1)
遍历数组中的所有整数,一旦找到结果立即返回。
public int[] twoSum(int[] nums,int target)
{
int[] result=new int[2];
boolean isFind=false;
for(int i=0;i<nums.length-1;i++)
{
for(int j=i+1;j<nums.length;j++)
{
if(nums[i]+nums[j]==target)
{
isFind=true;
result[0]=i;
result[1]=j;
break;
}
}
if(isFind)
break;
}
return result;
}
解法二——时间复杂度O(N2)
使用HashMap,来建立数字和其坐标位置之间的映射,然后遍历数组。遍历数组时,用target减去遍历到的数字,就是我们需要的另一个数字了,直接在HashMap中查找其是否存在就可以了。
public int[] twoSum1(int[] nums,int target)
{
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++)
{
if(map.containsKey(target-nums[i]))
{
return new int[]{map.get(target-nums[i]),i};
}
else
{
map.put(nums[i], i);
}
}
return null;
}
- 查看了一些人的答案发现很多人说,此处有一点需要注意,因为题目中已经说明数组中的每个数字只出现一次,若是允许数组中有重复的数字,则需要检查在HashMap中查找到的符合条件的数字的索引是不是重复的。但是仔细思考觉得应该是不会找到同一个索引的数字的。比如数组为{2,4,3,6,7,2,4,2,6,3,7},无论用方法一还是方法二答案都是唯一的{0,5}。
- 再次查找资料想起来有一个注意事项,HashMap中的Key是唯一的,但是这个地方不用考虑这个问题,因为若是数组中有重复数字则不需要考虑第一次出现之后再次出现的重复数字,就算刚好两个重复数字加起来为target,也可以通过方法二得到想要的结果。