1. Two Sum - 两数之和

https://leetcode.com/problems/two-sum/

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目分析:从整型数组中返回和为给定值的两个数的下标,每个下标元素只能使用一次

暴力法:遍历每个元素 x,并查找是否存在一个值与 target - x 相等的目标元素,两层for循环时间复杂度 O(n^2)

        for(int i = 0; i < nums.length; i++){
            for(int j = i + 1; j < nums.length; j++){
                if(target == nums[i] + nums[j]){
                    return new int[]{i,j};
                }
            }
        }

引入Hash表:建立数组中的每个元素与其索引的映射,先循环将元素放入map,再循环检测是否已经存在当前元素所对应的目标元素;

保持数组中的每个元素与其索引相互对应的最好方法是什么?哈希表,通过以空间换取速度的方式,我们可以将查找时间从 O(n)降低到 O(1); 哈希表正是为此目的而构建的,它支持以 近似 恒定的时间进行快速查找;

("近似" 是因为一旦出现冲突,查找用时可能会退化到 O(n),但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为 O(1))

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            //每个元素只能用一次
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
        }

 在测试参数有多个答案时,因为map中后续索引被覆盖的缘故,重复元素取的是最后一个的索引,如 nums = [2,5,5,6], target = 11,返回[2,3]而不是[1,3];

优化:在进行迭代并将元素插入到表中的同时,检查表中是否已经存在当前元素所对应的目标元素

   static int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            int complement = target - nums[i];
            if(map.containsKey(complement)){
                return new int[]{map.get(complement),i};
            }
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值