LeetCode 面试题 02.01. 移除重复节点


题目

在这里插入图片描述


思路

用一个Set集合保存每个节点的值,使用一前一后双指针,如果后指针遍历到的节点值出现过,则说明该节点为重复节点,则修改前指针的next指针的对象指向,删除重复节点。如果后指针遍历到的节点值没有出现在Set中,则前后指针都往后移动即可。


代码实现(Java)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head == null){
            return head;
        }
        Set<Integer> set = new HashSet<Integer>();
        ListNode res = head;
        ListNode next = head.next;
        set.add(head.val);
        while(next != null) {
            if(set.contains(next.val)){
                head.next = next.next;
            } else {
                set.add(next.val);
                head = head.next;
            }
            next = head.next;
        }
        return res;
    }
}

深度思考

我用了HashMap 和 HashSet 都实现了一遍,对比时间效率,发现 HashMap 的时间消耗更大,如下图

HashMap实现

在这里插入图片描述

HashMap对应的实现代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head == null){
            return head;
        }
        HashMap<Integer,Integer> set = new HashMap<Integer,Integer>();
        ListNode res = head;
        ListNode next = head.next;
        set.put(head.val,head.val);
        while(next != null) {
            if(set.containsValue(next.val)){
                head.next = next.next;
            } else {
                set.put(next.val,next.val);
                head = head.next;
            }
            next = head.next;
        }
        return res;
    }
}

HashSet实现

在这里插入图片描述

思考

HashSet 的底层是用HashMap实现的,查看 contains 的源码发现
在这里插入图片描述
我用HashMap实现的时候,使用的是 HashMap 的 containsValue 实现,所以时间复杂度更高,将 containsValue 改为 containsKey 实现后,效率就和HashSet 一样高了。


总结

在利用 HashMap 判重的时候,尽量使用 containsKey 实现,这样子复杂度会更低。然后要多看源码,多思考底层数据结构实现。


坚持分享,坚持原创,喜欢博主的靓仔靓女们可以看看博主的首页博客!
您的点赞与收藏是我分享博客的最大赞赏!
博主博客地址: https://blog.csdn.net/weixin_43967679

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jiachengren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值