Leetcode-[难度中] 两数之和

题目描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

题目解析

思路:使用查找表来解决该问题。

设置一个 hashmap 容器 record 用来记录元素的值与索引,然后遍历数组 nums。

  • 每次遍历时使用临时变量 diff 用来保存目标值与当前值的差值

  • 在此次遍历中查找 record ,查看是否有与 diff 一致的值,如果查找成功则返回查找值的索引值与当前变量的值 i

  • 如果未找到,则在 record 保存该元素与索引值 i

Coding

public class TwoSum {

    private static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> record = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (record.containsKey(diff)) {
                return new int[]{record.get(diff), i};
            }
            record.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }

    public static void main(String[] args) {
        int[] nums = {2, 5, 7, 11};
        int[] index = twoSum(nums, 9);
        if (index.length == 2) {
            System.out.println(index[0]);
            System.out.println(index[1]);
        }
    }

}

感谢你的关注,请关注作者公众号:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章