查看: 964| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] Two Sum算法的小trick(Leetcode的premium的解答没有讲到的)

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 fitness_sf 于 2022-1-28 07:43 编辑

Two Sum可以算是最简单的题了。不过还是有一些小细节。大家觉得有帮助给点分呗😂
下面是题目和LeetCode Premium给出的一个SolutionO(N) Solution.
题目:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

下面是Two Pass O(N)时间复杂度的解答:





To improve our runtime complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to get its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.

We can reduce the lookup time from O(n) to O(1) by trading space for speed. A hash table is well suited for this purpose because it supports fast lookup in near constant time. I say "near" because if a collision occurred, a lookup could degenerate to O(n) time. However, lookup in a hash table should be amortized O(1) time as long as the hash function was chosen carefully.

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums, 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) };
            }
        }
        // In case there is no solution, we'll just return null
        return null;
    }
}

LeetCode里面没有说的是第一个loop可能存在两个未知的数字相同的情况。这样loop结束以后map里面的value就是最后出现那个数字的位置。比如说[1,2,3,2],map里面是[2,3] 而不是[2,1]。 但是这个解答依然是对的是因为第二个循环一定是从小到大循环的,这样就不会出现重复使用同一个位置的数字的情况。但是如果把第二个循环倒序的话,算法就错了。

可能有人会问如果是【1,2,2,2,3】,同一个数字出现三个怎么办?其实题目是要求是可以假定结果只有唯一解,如果有三个的话就可能会有多个解了。算法终归是算法,two sum的题目本身简化了很多东西,所以这种hash的算法在真实场景中,没有那些限定条件的话,还是会有bug的。
[/i]
[i]附上one pass吧:[/i]
[i]class Solution {[/i]
[i]    public int[] twoSum(int[] nums, int target) {[/i]
[i]        Map<Integer, Integer> map = new HashMap<>();[/i]
[i]        for (int i = 0; i < nums.length; i++) {[/i]
[i]            int complement = target - nums[i];[/i]
[i]            if (map.containsKey(complement)) {[/i]
[i]                return new int[] { map.get(complement), i };[/i]
[i]            }[/i]
[i]            map.put(nums[i], i);[/i]
[i]        }[/i]
[i]        // In case there is no solution, we'll just return null[/i]
[i]        return null;[/i]
[i]    }[/i]
[i]}


[/i]

评分

参与人数 2大米 +9 收起 理由
sunny80 + 1 欢迎分享你知道的情况,会给更多积分奖励!
14417335 + 8 给你点个赞!

查看全部评分


上一篇:为什么我的solution总是不能AC?
下一篇:求问一道greedy的题目
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表