【LeetCode】142 - Linked List Cycle II

news/2024/7/3 17:43:32

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

Solution:

Discuss上的分析:Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nrNow, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node ism, so...s=k-m, s=nr-m=(n-1)r+(r-m),here we takes n = 1..so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *detectCycle(ListNode *head) {if(!head || !head->next)return NULL;ListNode *faster = head;ListNode *slower = head;while(faster->next && faster->next->next){faster=faster->next->next;slower=slower->next;if(faster==slower){ListNode *temp=head;while(temp!=slower){temp=temp->next;slower=slower->next;}return temp;}}return NULL;}
};

 

转载于:https://www.cnblogs.com/irun/p/4739753.html


http://lihuaxi.xjx100.cn/news/244566.html

相关文章

基于Springboot的生活方式分享平台的设计与实现

需求: 由前台和后台管理两个部分组成。前台作为与用户直接交互的可视化界面,主要功能包括:用户登录、用户注册、首页浏览查看热门笔记分享、切换笔记分类、点赞评论收藏笔记、查看用户主页关注用户、搜索相关笔记或用户等。用户拥有个人中心…

面试题:2018最全Redis面试题整理

1、什么是Redis?Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。 Redis 与其他 key - value 缓存产品有以下三个特点:Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次…

[喵咪的Liunx(1)]计划任务队列脚本后台进程Supervisor帮你搞定

喵咪的Liunx(1)]计划任务队列脚本后台进程Supervisor帮你搞定 前言 哈喽大家好啊,好久不见啊(都快一个月了),要问为什么没有更新博客呢只应为最近在录制PhalApi的视频教程时间比较少,作为弥补那么为大家带来一点干货Supervisor,话不多说那么就开始今天的分享把 附上: 喵了个咪的…

[转] splice系列系统调用

关注splice系列系统调用(包括splice,tee和vmsplice)已经有一段时间了,开始的时候并未能领会splice的意义所在,致使得出了“splice系列系统调用不怎么实用”的错误结论。随着内核研究的深入,才逐渐懂得&…

页面上表格金额统计汇总

页面结构&#xff1a; <!-- 核销退房结算 --> <div id"div-checkout-id" class"row cl"> <label class"form-label col-sm-1"><span class"c-red">退房结算</span></label>…

Windows 消息循环(1) - 概览

本文从消息循环是如何驱动程序的这个角度&#xff0c;对 Windows 消息循环进行概览性介绍。 使用 EN5 课件获得更好的阅读体验&#xff1a; 【希沃白板5】课件分享 : 《Windows培训 - 消息循环》https://r302.cc/q2d1jB 点击链接直接预览课件 1 程序是怎么跑起来的&#xff1f;…

PostgreSQL 批量权限 管理方法

关于PostgreSQL的逻辑架构和权限体系&#xff0c;可以参考 https://yq.aliyun.com/articles/41210 本文将给大家介绍一下如何批量管理表&#xff0c;视图&#xff0c;物化视图的权限。 以及如何管理默认权限&#xff0c;批量赋予schema的权限。 对整个schema的对象进行权限管理…

sublime text3 前端插件介绍

Emmet插件 Emmet插件可以说是使用Sublime Text进行前端开发必不可少的插件 它让编写HTML代码变得极其简单高效 基本用法&#xff1a;输入标签简写形式&#xff0c;然后按Tab键 关于Emmet的更多介绍&#xff0c;请查看官方文档 这份速查表&#xff0c;可以帮你快速记忆简写形式 …