其他分享
首页 > 其他分享> > 面试题 02.01. 移除重复节点

面试题 02.01. 移除重复节点

作者:互联网

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

示例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;
        
        

    }

 

标签:面试题,set,cur,02.01,head,next,链表,移除,null
来源: https://www.cnblogs.com/cocobear9/p/13194824.html