2022.1.9 每日一练 两数之和

阅读 22

2022-01-09

如有错误请提出!谢谢

答案选A

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int distance = target - nums[i];
            if (cache.containsKey(distance)) {
                return new int[] { cache.get(distance), i };
            } else {
                cache.put(nums[i], i);
            }
        }
        return new int[] {};
    }
}

通过HashMap去存储读取到的每一个数的位置以及它与target的插值

每次循环将得到的数与HashMap中所得到之前每个数的差对比,当两者相等时,则输出两数位置

精彩评论(0)

0 0 举报