给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
输入:nums = [3,3], target = 6
输出:[0,1]暴力解法就是两层for循环,时间复杂度是On方,所以比较好的方案是哈希映射
哈希映射
(nums[i],i) 存入 map 中,继续遍历直到找到为止暴力解法,时间复杂度On方
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
res[0] = i;
res[1] = j;
break;
}
}
}
return res;
}
}哈希映射
class Solution {
HashMap<Integer, Integer> map = new HashMap<>();
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
}