目录/Table of Content
82. Remove Duplicates from Sorted List II (移除有序链表中的重复项之二)
大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
题目描述
这道题目先给一 个有序链表,然后我们要做的就是找出当中的重复项,把它们完全刪除,只留下在原链表中没有重复过的数字。
理解上倒也不难,但是写出来的算法必须可以判断有哪些数项是已经重复过並把它们刪除。如果写得不够准确,有可能会出现不小心留下一个重复项,然后跟其它项对比它就变成唯一项,那就会出错。
题目原文(英语)
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.
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
解题方式
我的方法是:先建立两个指针 (previous
和 curr
),分別放前一个数项和现在检查的数项,利用curr
和有序的特性,来找出连续出现的数字,最后用previous
和 previous.next
来跳过它们。最后留下来的,就是没有重复过的数字。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None:
return head
previous = None
curr = head
while curr and curr.next is not None:
if curr.val != curr.next.val:
previous = curr
curr = curr.next
elif curr.val == curr.next.val:
while curr.next and curr.val == curr.next.val:
curr = curr.next
if not previous:
head = curr.next
curr = head
elif curr is not None:
previous.next = curr.next
curr = curr.next
else:
previous.next = None
return head