zoukankan      html  css  js  c++  java
  • Leetcode 82. Remove Duplicates from Sorted List II

    Description: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

    Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

    Examples:

    Example 1:
    Input: 1->2->3->3->4->4->5
    Output: 1->2->5
    
    Example 2:
    Input: 1->1->1->2->3
    Output: 2->3

    思路: 和83的区别在于,1) 只要这个元素出现过两次及以上,就删除,所以当前元素不仅要和前面的比较,还要和后面的比较,当与前后都不同时,才被添加到返回链表中,2) pre的更新也不同,83中,当pre和当前值不同时,才更新,相同则不更新,这里要随着指针移动而更新。3) 注意return linked list的head,如果从链表的第二个元素开始遍历,需要先确认第一个元素是否unique.

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution(object):
        def deleteDuplicates(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head: return head
            if not head.next: return head
            
            rhead = ListNode(0)
            r = rhead
            pre = head.val
            p = head.next
            if pre != p.val:
                r.next = head
                r = r.next
            while p:
                if p.val != pre and (p.next is None or p.val != p.next.val):
                    r.next = p
                    r = r.next
                pre = p.val
                p = p.next
            r.next = None
            return rhead.next           

    日期: 2020-11-17 周二就又过去了半天

  • 相关阅读:
    函数之返回值
    函数之初识函数
    三元运算符
    枚举enumerate
    模块
    迭代器
    斐波那契
    leetcode155 最小栈
    leetcode94 二叉树的中序遍历
    leetcode20 有效的括号
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/13993602.html
Copyright © 2011-2022 走看看