[LeetCode]题解(python):142-Linked List Cycle II
2016-05-09 17:01
489 查看
[b]题目来源:[/b]
https://leetcode.com/problems/linked-list-cycle-ii/
[b]题意分析:[/b]
给定一个链表,如果链表有环,返回环的起始位置,否则返回NULL。要求常量空间复杂度。
[b]题目思路:[/b]
首先可以用快慢指针链表是否有环。假设链表头部到环起点的距离为n,环的长度为m,快指针每次走两步,慢指针每次走一步,快慢指针在走了慢指针走t步后相遇,那么相遇的位置是(t - n) % m + n=(2*t - n)%m + n,那么得到t%m = 0,所以头部和相遇的位置一起走n步会重新相遇。那么,头部和相遇点再次走,知道相遇得到的点就为起点。
[b]代码(python):[/b]
View Code
https://leetcode.com/problems/linked-list-cycle-ii/
[b]题意分析:[/b]
给定一个链表,如果链表有环,返回环的起始位置,否则返回NULL。要求常量空间复杂度。
[b]题目思路:[/b]
首先可以用快慢指针链表是否有环。假设链表头部到环起点的距离为n,环的长度为m,快指针每次走两步,慢指针每次走一步,快慢指针在走了慢指针走t步后相遇,那么相遇的位置是(t - n) % m + n=(2*t - n)%m + n,那么得到t%m = 0,所以头部和相遇的位置一起走n步会重新相遇。那么,头部和相遇点再次走,知道相遇得到的点就为起点。
[b]代码(python):[/b]
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None or head.next == None: return None slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: tmp = head while tmp != fast: tmp,fast = tmp.next,fast.next return tmp return None
View Code
相关文章推荐
- wxpython最小化图标的创建
- python查询IP对应的地理位置
- Python 数据分析包:pandas 基础
- Python sort( ) sorted( ) reverse( ) reversed( ) 总结
- Python pip distribute
- python reverse()方法
- wxPython-多个按钮使用同一个回调函数
- python 装饰器 中的 *args 和 **kwargs
- 爬取分页的标题
- Python学习路程day14
- python 以十六进制输出字符串
- python sort()方法
- python内置模块string源码浅析之maketrans
- python爬虫问题:error: command 'gcc' failed with exit status 1
- Mac OS X下搭建Python3.5.1+PyQt5.6开发环境
- vagrant系列教程(五):vagrant搭建python开发环境
- Python自然语言处理
- Python编程入门
- Python 并发
- python 内置函数 reversed()