题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target的那两个整数,并返回它们的数组下标。
方法一:暴力枚举
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++){
int sum=nums[i]+nums[j];
if(sum==target){
return new int[]{i,j};
}
}
}
return new int[0];
复杂度分析
时间复杂度: O(N2 ),其中 N 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。
空间复杂度:O(1)。
方法二:哈希表
创建一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hash=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(hash.containsKey(target-nums[i])){
return new int[]{hash.get(target-nums[i]),i};
}
hash.put(nums[i],i);
}
return new int[0];
}
复杂度分析
时间复杂度:O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1)地寻找 target - x。
空间复杂度:O(N),其中 N是数组中的元素数量。主要为哈希表的开销。