LeetCode 1. Two Sum
1.暴力检索
从第1个元素开始,依次与它后面的每个元素相加,看是否等于target,之后再从第2个元素开始重复相同的步骤。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
if (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) {
result[0] = i;
result[1] = j;
return result;
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
} 2.用HasMap保存数组元素与其索引的对应关系
先遍历一遍该数组,时间复杂度为O(n),保存的键值对为 元素-索引,这样只需要O(1)的时间就能使用map.get(键值)来获取每个元素对应的索引值。
class Solution {
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++) {
// 看看target - nums[i]之后的值在不在map中,如果在的话则配对成功
int rest = target - nums[i];
if (map.containsKey(rest) && map.get(rest) != i) {
return new int[]{i, map.get(rest)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
} 3.用HashMap,边遍历边存储,一旦发现有符合的结果在HashMap中,则立刻返回
class Solution {
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");
}
}
