两数之和_LeetCode01


两数之和_LeetCode01

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

分析

第一个版本中我只是用到了一个最基本的冒泡的方式遍历了数组进行的查询,目前代码如下:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] array = new int[]{0,0};
        for(int i = 0;i<nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                if((target - nums[i] - nums[j]) == 0 ){
                    array[0] = i;
                    array[1] = j;
                }
            }
        }
        return array;
    }
}
  • 执行结果
    tPS9bT.png

第二个版本思路本来是想先将不可能的数进行一次排除后再进行求和,后来发现存在可为负数的情况。因此这种方案失败。最后推荐一种官方给出的解题思路一次Hash法

public int[] twoSum1(int[] nums, int target) {
    Map<Integer,Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int difference = target - nums[i];
        if(map.containsKey(difference)){
            return new int[] {map.get(difference),i};
        }
        map.put(nums[i],i);
    }
    throw new IllegalArgumentException("No two sum solution");
}
  • 执行结果
    tPPwXn.png

这种方法最最主要的特定是利用了HashMap中的key只能映射一个元素。通过这样的特性使得在一次遍历中可以去map中寻找是否存在差值。这是一种空间加hash来换取时间的方法。


  TOC