问题描述

  • 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
  • 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
  • 你可以按任意顺序返回答案。

  • 示例 1:

    1
    2
    3
    输入:nums = [2,7,11,15], target = 9
    输出:[0,1]
    解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
  • 示例 2:
    1
    2
    输入:nums = [3,2,4], target = 6
    输出:[1,2]
  • 示例 3:
    1
    2
    输入:nums = [3,3], target = 6
    输出:[0,1]

解决方法

1.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
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++){
if(nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[0];
}
}
  • 思路:这个方法就是遍历数组中的元素X,然后继续遍历数组中X元素之后的元素,查看有没有target-X。

    2.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class Solution {
    public int[] twoSum(int[] nums, int target) {

    HashMap<Integer,Integer> map = new HashMap<>();
    int[] res = new int[2];
    for (int i = 0; i <nums.length; i++) {
    if (map.containsKey(target-nums[i])){
    res[0]=i;
    res[1]=map.get(target-nums[i]);
    return res;
    }else {
    map.put(nums[i],i);
    }
    }
    return res;
    }
    }
  • 思路:因为解决方法一时间复杂度较高,参考他们的做法,发现一种时间复杂度低的办法,就是只循环一次,先判断哈希表key中有没有target-nums[i],如果有的话,就直接返回新数组{i,map.get(target-nums[i])},如果没有,把数组的值作为map的key,数组下标作为value存到map中。