leetcode python3 简单题83. Remove Duplicates from Sorted List

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第八十三题

(1)题目
英文:
Given a sorted linked list, delete all duplicates such that each element appear only once.

中文:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list

(2)解法
① 使用双指针
(耗时:52ms,内存:13.8M)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        dummy_head = ListNode(None)
        dummy_head.next = head

        previous = dummy_head
        current = head

        while current:
            if previous and current.val == previous.val:
                previous.next = current.next
                current.next = None
                current = previous.next
                continue

            previous = current
            current = current.next
        return dummy_head.next

注意:
1.ListNode(0)和ListNode(None)都可以,因为反映的都是当前的表的值为空(if判断时)。
2.只有xx.next= 这样的形式才会改变xx连接的下一个表。

② 递归法,有两种
一种:
(耗时:60ms,内存:13.7M)

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        
        child = self.deleteDuplicates(head.next)
        if child and head.val == child.val:
            head.next = child.next
            child.next = None
            
        return head

注意:
1.这里的思路是:
只要head不为空,就会进行一次递归,所以会一直递归,直到head.next为None,开始返回值,child为最后一个表,如果这个表与前一个表的值是相同的,则前一个表(head)将连接到None,也就是跳过了重复的child,再返回head,然后重复以上的返回过程即可。
2.child.next = None其实是多余的,因为最后返回的是head,跟child没有关系的,并且去掉后,(耗时:44ms,内存:13.7M)。

另一种:
(耗时:52ms,内存:13.8M)

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        p = head
        while p and p.val == head.val:
            p = p.next
        head.next = self.deleteDuplicates(p)
        return head

注意:
1.调用递归函数的时候里面的head,p只是局部变量,不会影响上一次递归结果中的head,p。
2.or not head.next其实是多余的,并且当执行到最后一次递归时,head=None,所以head.next是不存在的,所以会报错的,并且去掉后,(耗时:48ms,内存:13.7M)。
3.这个方法与第一种是相反的思路哦。

最后,感谢Leetcode解答区大神们的思路,这里我主要是分析code的过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值