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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
解决:
问题是要从数组中找到两个数据,使得两数之和等于目标值,输出该两数的下标(从0开始)。显而易见,这里最简单的是O(n^2)
的时间复杂度的解决办法。
public static int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
A:for (int i = 0; i < nums.length; ++i){
answer[0] = i;
int b = target - nums[i];
for (int j = i + 1; j < nums.length; ++j){
if (nums[j] == b){
answer[1] = j;
break A;
}
}
}
return answer;
}
考虑O(n)
的算法,可以使用map
使得查找的复杂度降为O(1)
。
public int[] twoSum(int[] nums, int target) {
int[] answer = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i){
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; ++i){
int b = target - nums[i];
if (map.containsKey(b) && i != map.get(b))
return new int[]{i, map.get(b)};
}
return answer;
}
代码地址(附测试代码):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/TwoSum