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




方法一思路:

转list去重,再新建链表返回结果。

注,本题结果要保留节点的原顺序

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 转list
        tar = []
        while head:
            tar.append(head.val)
            head = head.next
        # 删除list中的重复元素且保留原序
        ans = []
        num = 0
        for i in range(len(tar)):
            if tar.count(tar[i]) == 1:
                ans.append(tar[i])
                num += 1
        # 转链表返回
        pre = node = ListNode(-1)
        for j in range(num):
            node.next = ListNode(0)
            node.next.val = ans[j]
            node = node.next
        return pre.next

方法二思路:

用字典统计。

用例 [-3,-1,-1,0,0,0,0,0,2] 返回值是:[2,-3],预期结果是:[-3,2],没能保持原序,蓝瘦。

class Solution(object):
    def deleteDuplicates3(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        prev = head.next
        while prev:
            print("test:", prev.val)
            prev = prev.next
        dictval = {}
        while head:
            if head.val not in dictval:
                dictval[head.val] = 1
            else:
                dictval[head.val] += 1
            head = head.next

        # 转链表返回
        pre = node = ListNode(0)
        for key, value in dictval.items():
            if value == 1:
                node.next = ListNode(0)
                node.next.val = key
                node = node.next
        return pre.next

代码三:

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        ans = ListNode('a')
        ans.next = head
        pre, cur = None, ans
        while cur:
            pre = cur
            cur = cur.next
            while cur and cur.next and cur.val == cur.next.val:
                temp = cur.val
                while cur and cur.val == temp:
                    cur = cur.next
            pre.next = cur
        return ans.next
posted @ 2020-05-16 12:55  人间烟火地三鲜  阅读(156)  评论(0编辑  收藏  举报