leetcode——82. 删除排序链表中的重复元素 II

简直痛哭流涕!!!!!

又一次做出来了链表题,而且是中等难度!!!而且效果不错!!!!

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return
        if head.next==None:
            return head
        if head.val==head.next.val and head.next.next==None:
            return
        r=head
        p=head.next
        q=p.next
        while p:
            if r.val==p.val:
                #print(r.val)
                a=r.val
                r=q
                #print(a)
                while r.val==a and r.next!=None:
                    r=r.next
                if r.val==a:
                    return
                head=r
                #print(r.val)
                if r.next!=None:
                    p=r.next
                else:
                    return head
                #print(p.val)
                if p.next!=None:
                    q=p.next
                else:
                    if r.val==p.val:
                        return 
                    return head
            elif p.next!=None and p.val==q.val:
                b=p.val
                if q.next==None:
                    r.next=None
                    return head
                p=q.next
                while p.val==b and p.next!=None:
                    p=p.next
                #print(r.val,p.val,b)
                if p.val==b:
                    r.next=None
                    return head
                q=p.next
                r.next=p
                #print(r.val,p.val,q.val)
            else:
                if r.next==None:
                    return head
                else:
                    r=r.next
                if p.next==None:
                    return head
                else:
                    p=p.next
                if q.next==None:
                    return head
                else:
                    q=q.next
        return head
执行用时 :48 ms, 在所有 python3 提交中击败了94.44%的用户
内存消耗 :13.9 MB, 在所有 python3 提交中击败了5.26%的用户
 
但是看看人家的例子,好简洁:
执行用时为 36 ms 的范例
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head: return head
        dummy = ListNode(0)
        dummy.next = head
        slow, fast = dummy, head
        while fast:
            while fast.next and fast.next.val == fast.val:
                fast = fast.next
            if slow.next == fast:
                slow = fast
            else:
                slow.next = fast.next
            fast = fast.next
        return dummy.next

 

 

 

                                                  ——2019.10.23

 
posted @ 2019-10-23 22:08  欣姐姐  阅读(164)  评论(0编辑  收藏  举报