问题:
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.
代码示例:
1、暴力解法
public class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length < 2) {
return null;
}
for(int i = 0; i < nums.length - 1; ++i) {
for (int j = i + 1; j < nums.length; ++j) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return null;
}
}
2、利用hashMap来快速查找
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
//求出需要的匹配数字
int complement = target - nums[i];
//判断匹配数字是否已经加入到map中
//更快,而且可以避免加入重复数字时HashMap的替换
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}