当前位置: 首页 > news >正文

力扣刷题Day 31:删除链表的倒数第N个结点(19)

1.题目描述

2.思路

方法1:两遍遍历,第一遍获取链表长度,第二遍到达指定位置删除指定结点。

方法2:递归,一趟扫描即可实现,但可能是因为我的思路太混乱,代码很繁琐而且空间复杂度也很高。

方法3:跟灵茶山艾府大佬学习的双指针方法。

3.代码(Python3)

方法1:

class Solution:def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:node = headlist_len = 0while node:list_len += 1node = node.nextnode = headif (list_len - n) == 0:return head.nextelif (list_len - n) != 1:for i in range(list_len - n - 1):node = node.nextnode.next = node.next.nextreturn head

方法2:

class Solution:def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:def helper(node):# 获取链表长度nonlocal list_lenlist_len += 1if not node.next:return (1, node, False)cur_n, next_node, find_or_not = helper(node.next)if cur_n == n + 1:if not find_or_not:find_or_not = Truereturn (cur_n, next_node, find_or_not)else:if list_len - n == 1:find_or_not = Truereturn (cur_n + 1, node, find_or_not)list_len = 0prior_node, find_or_not = helper(head)[1:]if find_or_not:if list_len - n == 1:prior_node = headprior_node.next = prior_node.next.nextreturn headelse:return head.next

方法3:

class Solution:def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:left = right =dummy = ListNode(next=head)for _ in range(n):right = right.nextwhile right.next:left, right = left.next, right.nextleft.next = left.next.nextreturn dummy.next

4.执行情况

方法1:

方法2:

方法3:

5.感想

两趟扫描竟然比一趟扫描的性能还要好一些。

相关文章:

  • 数据库原理(1)
  • 贝叶斯算法学习
  • 【LeetCode 热题 100】链表 系列
  • [实战] 卡尔曼滤波:原理、推导与卫星导航应用仿真(完整代码)
  • 深入剖析 TypeScript 基础类型:string、number、boolean 的声明与使用
  • lnmp1.5+centos7版本安装php8
  • ※※惯性时间常数与系统惯量定义、区别、联系
  • 数据结构手撕--【堆】
  • 【matlab】绘制maxENT模型的ROC曲线和omission curve
  • Java基础 — 循环
  • 深入解析 C++17 中的std::variant与std::visit:从原理到实践
  • Python函数基础:说明文档(多行注释),函数嵌套调用,变量作用域(局部,全局,global关键字),综合案例
  • PMP-第一章 引论
  • Linux 复制、移动命令总结
  • ADC介绍
  • Android 13 接入 MediaSession 详细文档
  • DP之书架
  • CANFD技术在实时运动控制系统中的应用:协议解析、性能测试与未来发展趋势
  • 数据可视化大屏——大数据分析系统
  • 【人工智能】Python中的深度学习模型部署:从训练到生产环境
  • 仲裁法修订草案二审稿拟增加规定规制虚假仲裁
  • 民航局答澎湃:督促各单位进一步完善航班大面积延误和大面积备降应急处置预案
  • 政治局会议深度|提出“设立新型政策性金融工具”有何深意?
  • 博物馆有一项活动40岁以上不能参加?馆方回应
  • 政治局会议:创新推出债券市场的“科技板”,加快实施“人工智能+”行动
  • 海南高院通报去年知产领域司法保护状况:审结民事一审案件4847起