给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
暴力解法:双for循环
时间复杂度 O(n2)
空间复杂度 O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
int a = 0;
int b = 0;
for(int i = 0;i < nums.length; i++){
int temp = target - nums[i];
for(int j = i + 1;j < nums.length; j++){
if(temp == nums[j]){
b = j;
a = i;
}
}
}
return new int[]{a,b};
}
}
哈希表
时间复杂度 O(n)
空间复杂度 O(n)
利用hashmap键值对的特性,对数组从头进行遍历,把数组值作为key,值的下标作为value。从nums[0]开始往hashtable里put。
put之前先做一个判断,判断此时的target与值的差值是否已经存在于hashtable中。
如果不存在,那就把key-value放入哈希表中。
如果存在,就说明找到了两数之和为target的两个数。此时提出他俩的下标放进数组return即可。
一个下标是当前循环中的i。另一个下标是key-value中的value,利用get(key)方法,去查询对应的value
记得给hashmap指定容量,能提高性能。
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int a = 0;
int b = 0;
Map<Integer,Integer> hashtable = new HashMap(len + 1);
for(int i = 0; i < len;i++){
if(!hashtable.containsKey(target - nums[i])){
hashtable.put(nums[i],i);
}else{
a = hashtable.get(target - nums[i]);
b = i;
}
}
return new int[]{a,b};
}
}