0
点赞
收藏
分享

微信扫一扫

2022.1.9 每日一练 两数之和

何以至千里 2022-01-09 阅读 22

如有错误请提出!谢谢

答案选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 条评论