leetcode: 82. Remove Duplicates from Sorted List II

来源:互联网 发布:怎么看手机端口 编辑:程序博客网 时间:2024/06/06 08:59

Q

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

AC

# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def deleteDuplicates(self, head):        """        :type head: ListNode        :rtype: ListNode        """        newhead = newtail = None        seen = dict()        p = head        pp = None        while p:            dup = False            while p.next and p.next.val==p.val:                dup = True                p = p.next            if not dup:                if not newhead:                    newhead=newtail= p                else:                    newtail.next = p                    newtail = p            p = p.next        if newtail:            newtail.next = None        return newhead# Time:  O(n)# Space: O(1)# Definition for singly-linked list.class ListNode:    def __init__(self, x):        self.val = x        self.next = None    def __repr__(self):        if self is None:            return "Nil"        else:            return "{} -> {}".format(self.val, repr(self.next))class Solution2(object):    def deleteDuplicates(self, head):        """        :type head: ListNode        :rtype: ListNode        """        dummy = ListNode(0)        pre, cur = dummy, head        while cur:            if cur.next and cur.next.val == cur.val:                val = cur.val;                while cur and cur.val == val:                    cur = cur.next                pre.next = cur            else:                pre.next = cur                pre = cur                cur = cur.next        return dummy.nextif __name__ == "__main__":    head, head.next, head.next.next, head.next.next.next, head.next.next.next.next, head.next.next.next.next.next, head.next.next.next.next.next.next\        = ListNode(1), ListNode(2), ListNode(3), ListNode(3), ListNode(4), ListNode(4), ListNode(5)    print Solution().deleteDuplicates(head)


原创粉丝点击