leetcode#142. Linked List Cycle II
来源:互联网 发布:淘宝流量是怎么计算的 编辑:程序博客网 时间:2024/06/04 00:54
Description
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
这题回忆满满呀。当初进实验室前,道佳面试我的时候就问了这题。当时临时想的就是最蠢的标记法,或者开数组存储遍历过的节点之类的…显然在不能修改链表和不知道链表有多长的时候,这种做法是不实际的。当时道佳就跟我说了快慢指针的做法,后来也和小嘎嘎讨论过这题,有次还仔细的思考了为啥俩指针速度要差一倍,可惜现在都忘了当初的思考结果了。
Code
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ slow = fast = head while slow != None and fast != None: slow = slow.next fast = fast.next if fast == None: return None else: fast = fast.next if fast == slow: break if fast == None: return None while head != fast: head = head.next fast = fast.next return head
Conclusion
网上的解释很多,随便一搜就有,此处只记录个算法。
http://blog.sina.com.cn/s/blog_6a0e04380101a9o2.html
阅读全文
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- 2.5撤销修改
- IntelliJ IDEA 设置代码提示或自动补全的快捷键 (附IntelliJ IDEA常用快捷键)
- 进程间的通信----socket通信
- 用算法去扫雷(go语言)
- python之split()使用方法和try-except块
- leetcode#142. Linked List Cycle II
- Java 并发工具包 java.util.concurrent 用户指南
- LeetCode题解 week11
- 摩尔定律还有效吗
- 【汽车口碑分析】1.Ubuntu 16.04 LTS下安装Scrapy
- Tomcat中manager详解
- 设计模式之外观模式
- Exception in thread "main" java.lang.UnsupportedClassVersionError
- 欢迎使用CSDN-markdown编辑器