题目描述
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.
Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路分析
1、暴力法(O(
n2
))
这种方式比较简单,两层循环。外层循环确定一个num[i],然后内层循环判断num[j]==target-num[i],如果为true就得到了结果。
时间复杂度为O(
n2
)
2、借助HashMap
数据结构中,数组寻址方便,通过下标就可以直接得到值,但是插入和删除比较困难。如果是直接在末尾插入,操作方便,但也存在数组越界的可能,需要检查数组容量并在超出范围后进行手动扩容,同时如果在中间进行插入,要依次向后移动数组元素,空出一个位置供新元素写入;而删除元素,则要把后面的元素依次向前移。对于链表,则是插入和删除简单,只需要修改指针,无需移动元素。但是访问时比较费时,比如对于单向链表,必须要从头节点开始遍历。
HashMap结合和数组和链表的优点,采用了数组和链表的组合方式,因此也叫“链表散列”。插入元素时,由key值通过hashcode找到对应数组的位置,放入横向数组的某个格子中。因为前面说到hashcode值不能保证唯一,即不同的key值会对应同一个数组下标,发生碰撞。如果之后hashcode值对应的数组位置中已经有值,就放到相连的链表中。查找元素也是按这个过程来进行。
利用HashMap我们可以一次遍历就能得到结果。当我们迭代并将元素插入到hashmap中时,我们还会回过头来检查当前元素的补充是否已经存在于hashmap中。如果它存在,我们就找到了一个解决方案并立即返回。
代码
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int res = target - nums[i];
if (map.containsKey(res)) {
return new int[] { map.get(res), i };
}
map.put(nums[i], i);
}
return new int[]{0,0};
}
或
public static int[] twoSum1(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i]))
{
return new int[]{map.get(nums[i]),i};
}else
{
map.put(target-nums[i], i);
}
}
return new int[]{0,0};
}