• 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
    
  • 相关阅读:
    15道谷歌面试题及答案
    Linux解压 tar命令
    C#中的WebBrowser控件的使用
    C#中正则表达式使用介绍
    C#中的DataGridView
    使用Python破解验证码
    Python Open Source Project List
    程序员接私活经验谈[转]
    C#中的Dictionary字典类介绍
    金老师的博客
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900001.html
Copyright © 2020-2023  润新知