LeetCode_Lined List CycleII
2024-04-30 04:47:56
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?
这道题让我很无语,感觉我的算法和AC的应该是一样的,但是就是TLE,贴出来:
/*** 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) {// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.ListNode* slow = head;ListNode* fast = head;do{if( !slow || !fast ) return NULL;slow = slow->next;fast = fast->next;if( fast ) fast = fast->next;else return NULL;}while( slow != fast );slow = head;while( slow != fast ){slow = slow->next;fast = fast->next;}return slow;}
};
上面是AC的,下面是自己写的TLE:
/*** 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==NULL){return NULL;}ListNode *pSingleSpeed=head;ListNode *pDpubleSpeed=head;while (pSingleSpeed!=NULL&&pDpubleSpeed!=NULL){pSingleSpeed=pSingleSpeed->next;pDpubleSpeed=pDpubleSpeed->next;if (pDpubleSpeed!=NULL){pDpubleSpeed=pDpubleSpeed->next;}/* else{return NULL;}*/if (pSingleSpeed==pDpubleSpeed/*&&pSingleSpeed!=NULL&&pDpubleSpeed!=NULL*/){break;}}if (pDpubleSpeed==NULL||pSingleSpeed==NULL){return NULL;}pDpubleSpeed=head;while (pDpubleSpeed!=pSingleSpeed){pSingleSpeed=pDpubleSpeed->next;pSingleSpeed=pSingleSpeed->next;}return pSingleSpeed;}
};
两者思想都是一样的,先判断是否具有回路,如果有,让一个指针回到起点,两个指针以相同速度继续走,在此相遇地点就是环的入口,如果不清楚,画图一看就知道了。
LeetCode_Lined List CycleII相关推荐
最新文章
- 算法科普:神秘的 DES 加密算法
- 分享一个centos不错的镜像库
- 无线网卡的Master,Managed,ad-hoc,monitor等模式
- 你不可不看的 Oracle RAC 日常基本维护命令
- 函数名的使用、闭包、生成器
- Python绘制直方图案例一则
- CSS 魔法:学海无涯,而吾生有涯
- SecureCRT问题
- 算法:有效九宫格数独Valid Sudoku
- 微信小程序模版合集下载,160个微信小程序源码.zip + 35个行业-微信小程序源码.zip
- python开发grasshopper插件_Rhino_Grasshopper_Python 开发的正确姿势
- 朋友:趣头条上市了!我:谁?
- android 播放流媒体_30个最佳和免费的Android媒体播放器
- edge搁置标签页_如何自定义Microsoft Edge的新标签页
- 关于相对论的一个猜想——二维空间理论
- matlab之矩阵输入(一)
- j3455文件服务器,看烦了千篇一律的J3455?让黑群晖显示真实的CPU信息
- 云渲染是什么?云渲染好处以及安装方法。
- ChatGPT教程之 05 ChatGPT 和你的工作
- python教学视频谁讲得好,python讲的比较好的视频
热门文章
- 借力《旅行青蛙》,阿里手游便可叫板腾讯、网易?
- UIPATH 收发Outlook邮件
- 在场景中增加固定自定义栏
- 【书 JS语言精粹】第4章 函数
- 基于随机游走Random Walk的图节点Node表示
- 《杜拉拉升职记》职场36计
- 前端使用Element-上传图片,图片转码位base64位传给后端,再获取后端数据展示图片
- Google Earth Engine(GEE)——Output of image computation is too large (29 bands for 828828 pixels = 96.
- 彩云小译怎么翻译网页_彩云小译插件,中英双语对照网页翻译,支持视频字幕翻译...
- MYSQL数据库系统第4次实验 单表查询