LeetCode——1 寻找两数之和为指定数

描述:

        输入:一个整数的数组,一个整数。寻找两个数之和为这个整数的所在下标(假设只有一组能满足)

       返回:一个Int[2] 的数组,得到两个数的下标。

又是一道简单题,不过明显感觉自己基础忘了不少,居然没想到用HashMap,第一反应就用了两个for。

先上自己的代码。再上HashMap的方法代码。

/*这是自己写的两个for*/

public static int[] twoSum(int[] nums, int target) {
        int numsLength = nums.length;
        for(int i = 1; i < numsLength; i++){
            for(int j = 0; j < i; j++){
                if(nums[j] + nums[i] == target){
                    return new int[] {j,i};
                }
            }
        }
        return nums;
    }

/*用到hashMap的节约时间的方法*/

 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");
    }

作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

这里有一个细节需要注意的,leetcode上的官方还有一种解法是先一次for,把数组都放进去,第二次for在查找。这是错的,因为如果输入的数组有两个值是一样的,那么第二个输入的就key值冲突了,这样丢失了一个数。这种一遍for的方法在放入Map前先查找,可以避免这种情况的发生。

猜你喜欢

转载自blog.csdn.net/lfanchenyu/article/details/104900068