给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解法一:JAVA,暴力枚举,时间复杂度O(n^2),空间复杂度O(1)
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};
}
}
解法二:JAVA,哈希表,时间复杂度O(n),空间复杂度O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int n=nums.length;
for(int i=0;i<n;i++)
{
//map.put(nums[i],i);
if(map.containsKey(target-nums[i]))
return new int[] {map.get(target-nums[i]),i};
map.put(nums[i],i);
}
return new int[] {0};
}
}
注意:
1、为避免查到的键为当前数本身,要先查询(if判断语句)当前数是否能与哈希表中的数求和得到target,再将当前数添加到哈希表中。
2、键与值分别对应保存,键->数组值,值->数组下标,原因是HashMap无法直接由value获得key,若键存储数组下标,值存储数组值,当发现HashMap中有需要的值时会无法获得该值对应的键,而不能返回正确数组下标。
Java中的HashMap:
HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。
HashMap 实现了 Map 接口,根据键的 HashCode 值存储数据,具有很快的访问速度,最多允许一条记录的键为 null,不支持线程同步。
HashMap 是无序的,即不会记录插入的顺序。
HashMap 继承于AbstractMap,实现了 Map、Cloneable、java.io.Serializable 接口。
方法:
containsKey() 检查 hashMap 中是否存在指定的 key 对应的映射关系。(检查是否存在键key)
get() 获取指定key对应的value
put() 将键值对添加到hashMap中
更多方法见:https://www.runoob.com/java/java-hashmap.html