zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    记第一场省选
    POJ 2083 Fractal 分形
    CodeForces 605A Sorting Railway Cars 思维
    FZU 1896 神奇的魔法数 dp
    FZU 1893 内存管理 模拟
    FZU 1894 志愿者选拔 单调队列
    FZU 1920 Left Mouse Button 简单搜索
    FZU 2086 餐厅点餐
    poj 2299 Ultra-QuickSort 逆序对模版题
    COMP9313 week4a MapReduce
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900001.html
Copyright © 2011-2022 走看看