美文网首页
面试题 02.01. 移除重复节点

面试题 02.01. 移除重复节点

作者: 漫行者_ | 来源:发表于2021-09-06 23:40 被阅读0次

面试题 02.01. 移除重复节点


看了题解。这个就是单纯循环暴力,然后找到对应的进行删除。
官方代码如下:

 public ListNode removeDuplicateNodes(ListNode head) {
        if (head == null) {
            return head;
        }
        Set<Integer> occurred = new HashSet<Integer>();
        occurred.add(head.val);
        ListNode pos = head;
        // 枚举前驱节点
        while (pos.next != null) {
            // 当前待删除节点
            ListNode cur = pos.next;
            if (occurred.add(cur.val)) {
                pos = pos.next;
            } else {
                pos.next = pos.next.next;
            }
        }
        pos.next = null;
        return head;
    }

用set的时候可以存Integer,没必要存对象。也可以判断
附上不满足题意,不正确的代码。用来删除重复对象的。

 public ListNode removeDuplicateNodes(ListNode head) {
        head = mergSort(head);
        ListNode p = head;
        while(p != null) {
            ListNode q = p.next;
            while(q != null && q.val == p.val) {
                q = q.next;
            }
            p.next = q;
            p = p.next;
        }
        return head;
    }

    public ListNode mergSort(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode quick = head;
        ListNode slow = head;
        while(quick.next != null && quick.next.next != null) {
            quick = quick.next.next;
            slow = slow.next;
        }
        ListNode helf = slow.next;
        slow.next = null;
        ListNode p = mergSort(head);
        ListNode q = mergSort(helf);
        ListNode temp = new ListNode(-1);
        ListNode n = temp;
        while(p != null && q != null) {
            if(p.val <= q.val) {
                n.next = p;
                p = p.next;
            } else {
                n.next = q;
                q = q.next;
            }
            n = n.next;
        }
        if(p != null) {
            n.next = p;
        } 
        if(q != null) {
            n.next = q;
        }
        return temp.next;
    }

相关文章

网友评论

      本文标题:面试题 02.01. 移除重复节点

      本文链接:https://www.haomeiwen.com/subject/izfuwltx.html