题目地址:leetcode-cn.com/problems/tw…
思路:一开始想到最笨的方法是利用两次循环去找到结果,但是算法时间复杂度为O(n2)。 其实我们可以利用hashmap来保存每次遍历的值,以<值,角标>的形式进行保存,每次循环内都去用目标值减去该次循环的值,判断是否在hashmap中存在。如果存在返回结果。达到只循环一次就能找到结果的目的。算法时间复杂度在O(n)
上代码:
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer,Integer> map = new HashMap<>();
for (int i =0;i < nums.length;i++) {
int val = nums[i];
int dest = target - val;
Integer val2 = map.get(dest);
if (val2 != null) {
result[0] = i;
result[1] = val2;
} else {
map.put(val, i);
}
}
return result;
}
}