LeetCode专项练习之快慢指针(Fast & Slow Pointers)笔记

本文是根据穷码农的LeetCode刷题建议而进行专项练习时记录的心得。

文章转自自己在知乎原创的同名文章https://zhuanlan.zhihu.com/p/107457778

快慢指针,作为双指针系列的一个分支,因为有着自己的特点,所以我在练习时把这一类题单独拿出来记录。今天的笔记包含快慢指针(Two Points)类型下的5个题目,它们在leetcode上的编号和题名分别是:

  • 141 - Linked List Cycle
  • 876 - Middle of the Linked List
  • 142 - Linked List Cycle II
  • 202 - Happy Number
  • 143 - Reorder List

下面将根据以上顺序分别记录代码和对应心得,使用的编译器为Python3。


Linked List Cycle

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

这道题我认为属于快指针的一个基础使用场景。在一开始做的时候,我原本以为快慢指针就是一个指针在前,一个指针在后,然后快指针在前面不断循环,若循环了一圈还不等于慢指针,就移动一次慢指针。咋一看,还挺适合这道题的。利用一个set存储快指针走过的节点,最后比对即可,但最后我发现这压根就不是快慢指针,而是单纯的双指针思路。所谓快慢指针,就是在同一个循环里,快慢指针同时移动,但快指针永远比慢指针多走几步(通常是2倍关系)。在知道了这个原则后,我便将它们放置于同一个循环里进行移动,只不过慢指针走一步,快指针走两步,直到快慢指针相遇/即将相遇或快指针走到尾部为止:

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        # my solution: 快慢指针。其中快指针永远比慢指针多走两步,如果快指针的下一个节点或者它本身的节点与慢指针相同,即一定有循环
        if head is None:
  
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值