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].
Time Limit Exceeded,这个算法的时间复杂度是O(n^2)
思路:可以事先将其存储起来,使用一个HashMap,来建立数字和其坐标位置之间的映射,我们都知道HashMap是常数级的查找效率,这样,我们在遍历数组的时候,用target减去遍历到的数字,就是另一个需要的数字了,直接在HashMap中查找其是否存在即可,注意要判断查找到的数字不是第一个数字,比如target是4,遍历到了一个2,那么另外一个2不能是之前那个2,整个实现步骤为:先遍历一遍数组,建立HashMap映射,然后再遍历一遍,开始查找,找到则记录index。
原代码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
m.put(nums[i], i);
}
for (int i = 0; i < nums.length; ++i) {
int t = target - nums[i];
if (m.containsKey(t) && m.get(t) != i) {
res[0] = i;
res[1] = m.get(t);
break;
}
}
return res;
}
}
改进代码:
//解决缺陷:若数组中有多组两数之和
public static List<int[]> twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
List<int[]> list=new ArrayList<int[]>();
for (int i = 0; i < nums.length; ++i) {
m.put(nums[i], i);
}
for (int i = 0; i < nums.length; ++i) {
int[] tmp = new int[2];
int t = target - nums[i];
//fix:!=改成>,避免重复
if (m.containsKey(t) && m.get(t) > i) {
tmp[0] = i;
tmp[1] = m.get(t);
list.add(tmp);//fix:nums中有多组符合条件
}
}
//解决缺陷:若数组中有多组两数之和
for(int i=0;i<list.size();i++){
System.out.println("list:"+list.size()+"--"+list.get(i)[0]+"And"+list.get(i)[1]);
}
return list;
}