题目原文:
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].
题目很简单,大意就是给你一个数组和一个目标值,要你找出数组中的两个数使得他们的和是目标值,这两个数以后定存在且不相同。
一般我们的思路就是O(n^2)的复杂度,两层循环嵌套来两两求和。但是看到推荐答案里面有一个O(n)复杂度的解法,很受启发,思路巧妙,值得贴出来:
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {//这里是重点,和map中存储的每个key比照,相当于一层循环
result[1] = i + 1;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i + 1);
}
return result;
}
当然,如果算上map的查找的时间耗费,复杂度肯定不止O(n)。