描述
给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1。
注意事项
你可以假设只有一组答案
样例
给出 numbers = [2, 7, 11, 15], target = 9, 返回 [1, 2]
挑战
Either of the following solutions are acceptable:
O(n) Space, O(nlogn) Time
O(n) Space, O(n) Time
代码
- hash 遍历 hash 表一次,时间复杂度 O(n),空间复杂度 O(n)
hash 表里键是数值的大小,值是数组的下标
public class Solution {
/*
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> hash = new HashMap<>();
int[] results = new int[2];
for (int i = 0; i < numbers.length; i++) {
int complement = target - numbers[i];
if (hash.containsKey(complement)) {
// 注意顺序,complement 早就加入了 hash,所以 complement 的 Index 比 i 小
// 下标从 1 开始
results[0] = hash.get(complement);
results[1] = i;
return results;
}
hash.put(numbers[i], i);
}
return results;
}
}
- 暴力解法两重for循环 时间复杂度O(n^2),空间复杂度O(1)
public class Solution {
/*
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
int[] results = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
results[0] = i;
results[1] = j;
return results;
}
}
}
return results;
}
}
- hash 遍历 hash 表两次,时间复杂度 O(n),空间复杂度 O(n)
public class Solution {
/*
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
int[] results = new int[2];
for (int i = 0; i < nums.length; i++) {
hash.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (hash.containsKey(complement)) {
results[0] = i + 1;
results[1] = hash.get(complement) + 1;
return results;
}
}
return results;
}
}