[leetcode:python]83.Remove Duplicates from Sorted List

来源:互联网 发布:淘宝一直不发货会怎样 编辑:程序博客网 时间:2024/05/22 02:06

题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.

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

方法一:性能59ms

# 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        """        if head == None:            return []        cur = head        while cur != None:            while cur.next != None and cur.val == cur.next.val:                cur.next = cur.next.next            cur = cur.next        return head

方法二:性能52ms

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param {ListNode} head    # @return {ListNode}    def deleteDuplicates(self, head):        if head == None:            return head        b = head        f = head.next        while f:            if f.val != b.val:                f.val, b.next.val = b.next.val, f.val                b = b.next            f = f.next        b.next = None        return head
0 0
原创粉丝点击