思路:
只需要找出数组中值等于 target-nums[i] 就解决了
第一种解决方法: 也是我自己的写的 时间负责度是O(N)
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length;i++){
for(int j = i+1; j < nums.length;j++){
if(target-nums[j]==nums[i]){
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("不存在这两个数");
}
}
第二种:(官方)
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 complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
他是将数组每一个元素先放在一个map中,map中存了n个元素,以空间换取时间的方式,
然后,在来一次循环,看看有没有符合上述条件的值,时间复杂度和空间复杂度都是O(N)
第三种
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。