码迷,mamicode.com
首页 > 其他好文 > 详细

面试题 02.01. 移除重复节点

时间:2020-06-26 14:27:05      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:cat   style   add   nod   开始   next   节点   problems   node   

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

示例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. 移除重复节点

标签:cat   style   add   nod   开始   next   节点   problems   node   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!