首页 > 其他 > 详细

面试题 02.01. 移除重复节点

时间:2020-06-26 15:01:28      阅读:79      评论:0      收藏:0      [点我收藏+]

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

示例1:

输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:

输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:

链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。

链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
思路:未排序+去重复-->想到用HashSet,刚开始就直接想把重复的元素去掉自己构建一个链表,这样有点麻烦,直接在遍历链表的时候利用HashSet去重即可

public static ListNode removeDuplicateNodes(ListNode head) {
        if(head == null) return null;
        Set<Integer> set = new HashSet<>();
        ListNode cur = head;
        //先把头元素放入set中
        set.add(cur.val);
        while(cur.next!=null) {
            if(set.contains(cur.next.val)) {
                //删除重复的元素
                cur.next = cur.next.next;
            }
            else {
                //不一样的元素放入set中
                set.add(cur.next.val);
                cur = cur.next;
            }
            
        }
        
        
        return head;
        
        

    }

 

面试题 02.01. 移除重复节点

原文:https://www.cnblogs.com/cocobear9/p/13194824.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!