美文网首页
code - 两数之和匹配目标值

code - 两数之和匹配目标值

作者: BestFei | 来源:发表于2020-04-11 20:12 被阅读0次

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

A:定义一个map存储数组中每个值对应的差值和自己的游标。
然后数组中每个值再去跟这个map的差值去匹配,匹配成功则返回游标

public class FindValue {
    public static int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length <= 1) {
            return new int[2];
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        // key 为每个数组对应的差值,value为数组的游标
        for (int i = 0; i < nums.length; i++) {
            map.put(target - nums[i], i);
        }
        // 数组里的每个值去和差值匹配,匹配上则返回差值对应数组里的游标
        for (int i = 0; i < nums.length; i++) {
            Integer v = map.get(nums[i]);
            // can't use itself
            if (v != null && v != i) {
                // 返回的是两个游标
                return new int[] { i , v };
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int[] nums = {2,3,5,7,11};
        int target = 9;
        int[] result = twoSum(nums,target);
        System.out.println(nums[result[0]]+"+"+nums[result[1]]+"="+target);
    }

}

相关文章

  • coding

    code - 获取质数code - 两数之和匹配目标值code - 最长有效字符串code - 字符的有效匹配co...

  • code - 两数之和匹配目标值

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

  • My Leetcode

    我的code 1.两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的...

  • leecode刷题(8)-- 两数之和

    leecode刷题(8)-- 两数之和 两数之和 描述: 给定一个整数数组 nums 和一个目标值 target,...

  • hashmap应用

    两数之和问题 题目描述:在给定的数组nums中找到两个数之和等于目标值target。 1. 暴力方法 检索数组中所...

  • LeetCode1.两数之和JavaScript

    LeetCode1.两数之和JavaScript 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可...

  • LeetCode 1. Two Sum

    给一组数,和一个值,求两个值之和等于目标值的索引

  • leet_code[两数之和]

    两数之和 代码: 初看有些纳闷,在自己机器上一跑,豁然开朗。1、enumerate 枚举整个list列表2、判断v...

  • 1.两数之和(Two Sum)

    1. 两数之和(Two Sum) 题目难度: 简单 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 ...

  • LeetCode:两数之和

    两数之和 题目叙述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两...

网友评论

      本文标题:code - 两数之和匹配目标值

      本文链接:https://www.haomeiwen.com/subject/kocpmhtx.html