原文链接:https://leetcode.com/problems/two-sum/solution/
问题描述
给定一个整数数组,返回两个整数的小标使得两个整数的和等于某个要求的整数。
数组 : [2, 7, 11, 15], 目标 : 9,
由于 nums[0] + nums[1] = 2 + 7 = 9,
返回 [0, 1].
解决方案
1、暴力匹配法
暴力匹配的思路很简单,直接用两个循环迭代即可。其示例代码如下:
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
2、hash表查找法
在暴力匹配法中第二个循环其实是用循环的方式去寻找另外一个值,此处可以非常容易的更换成hash表来提高检索速度。
public int[] twoSum(int[] nums, int target) {
Map<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 complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
3、hash表查找优化
hash表查找又分为两步,一部分是构建hash表,另一部分是构建hash表。可以考虑将两个步骤融合,即一边构建hash表,一边查找,这两个步骤本身就是互补干扰的。
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];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}