给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
哈希表方法
先将数组元素值和下标作为 key 和 value 存入 map ,再一次遍历,判断 keyset() 中是否存在 target - nums[i] 且 target-nums[i] 的下标不等于 nums[i] 的下标。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
map.put(nums[i], i);
}
for (int i=0; i<nums.length; i++) {
int component = target - nums[i];
if (map.keySet().contains(component) && map.get(component)!=i){
return new int[]{i, map.get(component)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度:O(N)
一遍哈希表方法
遍历数组,同时执行 put 操作和判断在 map 已存在的元素中是否有 component = target - nums[i] 。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
int component = target - nums[i];
if(map.keySet().contains(component)){
return new int[]{i, map.get(component)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度:O(N)
暴力解法
双重循环
public int[] twoSum(int[] nums, int target) {
for (int i=0; i<nums.length; i++) {
int component = target - nums[i];
for(int j=0; j<nums.length&&i!=j; j++) {
if (component == nums[j]) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度:O(N^2)
Cest la vie!