两数之和:在该数组中找出和为目标值的那两个整数,并返回他们的数组下标

题目描述:

  • 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
  • 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

  • 给定 nums = [2, 7, 11, 15], target = 9
  • 因为 nums[0] + nums[1] = 2 + 7 = 9
  • 所以返回 [0, 1]

嵌套for循环

    public static void main(String[] args) {
        int[] nums = {2, 4, 7, 5};
        int target = 9;
        for (int i = 0, len = nums.length; i < len; i++) {
            // 第二层for循环遍历余下的所有数值
            for (int j = i + 1; j < nums.length; j++) {
                int sum = nums[i] + nums[j];
                if (sum == target) {
                    int[] result = {i, j};
                    System.out.println (Arrays.toString (result));
                }
            }
        }
    }

 

利用hashMap,建立k-v,一一对应哈希表

    public static void main(String[] args) {
        int[] nums = {2, 4, 7, 5};
        int target = 9;
        int[] result = new int[2];
        HashMap<Integer, Integer> hashMap = new HashMap<> ();
        for (int i = 0, len = nums.length; i < len; i++) {
            // 判断数组中的值是否对应和的差值
            if (hashMap.containsKey (nums[i])){
                result[0] = hashMap.get (nums[i]);
                result[1] = i;
                System.out.println (Arrays.toString (result));
            }
            // 将差值作为key,下标作为value,存储到map
            hashMap.put (target - nums[i],i);
        }
    }

发布了65 篇原创文章 · 获赞 66 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44096448/article/details/104692141