题目
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
解答
方法一:暴力破解
class Solution {
public int[] twoSum(int[] nums, int target) {
int m, n;
int[] i = { 0, 0 };
for (m = 0; m < nums.length; m++) {
for (n = m+1; n < nums.length; n++) {
if (nums[n] + nums[m] == target) {
i[0] = m;
i[1] = n;
return i;
}
}
}
return i;
}
}
m遍历一遍数组,n遍历数组中索引大于m的数,因为不能使用两次相同的元素。
时间复杂度:O()
空间复杂度:O(1)
方法二:哈希表
将目标数组中的数值放在哈希表作为哈希表的键,数组的索引作为哈希表的值。遍历数组nums[i],检查哈希表中是否存在键=target-nums[i]的数据,
如果有,则满足条件,输出;
如果没有,则将该数据i和nums[i]存入哈希表
继续遍历下一个nums[i]的值,直到找到目标,或者跳出循环
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer>test=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(test.containsKey(target-nums[i])){
return new int []{test.get(target-nums[i]),i};
}
test.put(nums[i],i);
}
return new int[0];
}
}