题目:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
法一(暴力枚举法):
我的答案:
//暴力枚举法
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
int sum=nums[i]+nums[j];
if(target==sum){
return new int[]{i, j};
}
}
}
return new int[0];
}
}
官方答案:
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
复杂度分析:
时间复杂度:O(N^2),其中 NN 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。
空间复杂度:O(1)。
法二(哈希表)重点:
- 首先创建一个hash表
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
- 其次使用for循环遍历nums数组中的元素
for(int i=0;i<nums.length;i++)
- 如果hash表中存在target-nums[i]的值则代表已经找到要找的内容,将其输出
if(hashtable.containsKey(target-nums[i])){ return new int[]{hashtable.get(target-nums[i]),i}; }
- 若hash表中不存在该元素,将元素存入hash表中
hashtable.put(nums[i],i);
图解示例:
第一步:nums[]={4,9,11,4} target=15
num中的数值 | 4 | 9 | 11 | 4 |
位置 | 0 | 1 | 2 | 3 |
key | ||||
value |
第二步:
num中的数值 | 4 | 9 | 11 | 4 |
位置 | 0 | 1 | 2 | 3 |
key | 4 | 9 | ||
value | 0 | 1 |
第三步:
当前值num[i]=11,target-nums[i]=4在hash表中存在
num中的数值 | 4 | 9 | 11 | 4 |
位置 | 0 | 1 | 2 | 3 |
key | 4 | 9 | ||
value | 0 | 1 |
使用hashtable.get(target-nums[i])返回value值。值得注意的是:hash表中的key元素是nums的数值,value元素是在数组中的位置。
完整代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
//法二:hash表
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++){
if(hashtable.containsKey(target-nums[i])){
return new int[]{hashtable.get(target-nums[i]),i};
}
hashtable.put(nums[i],i);
}
return new int[0];
}
}