Leetcode141——Linked List Cycle
来源:互联网 发布:电子书什么软件好 编辑:程序博客网 时间:2024/06/04 00:49
题目:Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
开启自己的刷题之旅,尝试每两天刷一题左右,并把Solution都研究一下。
第一眼看这个题目,没有理解题目的意思,看成判断链表是否为循环链表,那这不是两个指针,一个不动一个不断移动,直到两者相等就可。
仔细研究才发现,是判断这个链表中是否有循环。一开始并没有思路。看了solution才发现,使用两个指针,walker每次移动一步,runner每次移动两步。然后判断两指针指向的内容是否相同。由于runner移动的是walker的两倍,存在循环的话,runner总能套walker的圈,“追”上他。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { if(head==NULL) return false; ListNode *walker = head; ListNode *runner = head; while(runner->next!=NULL && runner->next->next!=NULL) { walker = walker->next; runner = runner->next->next; if(walker==runner) return true; } return false; }};
但是这个答案的运行速度不是最快的。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { if(head == NULL || head -> next == NULL) return false; ListNode *fast = head; ListNode *slow = head; while(fast -> next && fast -> next -> next){ fast = fast -> next -> next; slow = slow -> next; if(fast == slow) return true; } return false; }};
这个答案比上一个时间缩短了不少,经过仔细阅读发现,在进入while循环之前,对head和head->next进行判断,因为存在循环至少要有两个结点。当两个结点存在空时,肯定不存在循环,这样就节约了时间。
感觉还是对于边界条件没有判断好!
0 0
- LeetCode141—Linked List Cycle
- Leetcode141——Linked List Cycle
- LeetCode141:Linked List Cycle
- leetcode141. Linked List Cycle
- leetcode141: Linked List Cycle
- leetcode141 Linked List Cycle
- LeetCode141. Linked List Cycle
- leetcode141. Linked List Cycle
- leetcode141~Linked List Cycle
- LeetCode141. Linked List Cycle
- leetcode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- leetcode141. Linked List Cycle
- LeetCode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- LeetCode141之Linked List Cycle java题解
- Redis底层数据结构之链表
- 最新iOS应用Beta测试分发app分发平台源码 Android应用内测分发平台源码免费仿蒲公英平台
- redis 集群配置实战
- linux/debian安装wps以及缺失字体,亲测可用
- DataTable相关资料
- Leetcode141——Linked List Cycle
- 浅谈Java的Comparator接口实现自定义排序Arrays.sort()
- linux中的粘滞位
- 剑指Offer 19 : 二叉树镜像
- PTA 5-28 猴子选大王
- mysql配置以及性能优化(转)
- 分享一个MySQL分库分表备份脚本(原)
- c 程序设计语言 第二版 练习题 5-1
- js:计时器