LeetCode-141 Linked List Cycle
来源:互联网 发布:淘宝流量如何申请退款 编辑:程序博客网 时间:2024/05/29 07:49
判定一个单链表中是否存在环。
设定快(fast)和慢(slow)两个指针,其中快指针每次前进m个节点,慢指针每次前进n( n < m)个节点。如果链表中存在环,那么fast和slow一定相遇,否则fast将首先遇到空指针(NULL)。
原理释义: 假设单链表的长度为N,并且为环状。那么在第i次迭代中,fast指向元素(n∗i) mod N 。因此, 当i=(m−n)∗i (mod N) 时,fast和slow相遇。(注:m-n需要满足一定的条件,才能保证二者一定相交,在最后进行推理)简单的代码实现:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public boolean hasCycle(ListNode head) { if(null == head) return false; ListNode slow = head, fast = head; while(fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast) return true; } return false;}
注: 原理推理,在一个环(长度为N)中, 如果两个指针的速度不一样, 0 < s < f ,其中s ,f 之间需要满足什么关系,一段时间后,保证两者相交?
我们将二者前进的距离表示为相同时间间隔 i 的具有相同性质的函数 :
Ds(i)=s∗i ,Df(i)=f∗i+k , 其中s, f为二者的前进速度, k为二者之间的初始距离。如果需要两者相较于一点, 那么有
Ds(i)=Df(i)=>(s∗i) modN=(f∗i+k) modN=>[(f−s)∗i+k]modN=0=>(f−s)∗i+k=K∗N(其中K为非负整数)=>i=N∗K−kf−s,其中f>s.
阅读全文
0 0
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [leetcode 141] Linked List Cycle
- [leetcode]141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- leetcode || 141、Linked List Cycle
- Leetcode[141]-Linked List Cycle
- leetcode-141-Linked List Cycle
- [Leetcode 141] Linked List Cycle
- leetcode 141: Linked List Cycle
- [Leetcode]#141 Linked List Cycle
- leetCode #141 Linked List Cycle
- leetcode: (141) Linked List Cycle
- [leetcode] #141 Linked List Cycle
- 【leetcode】【141】Linked List Cycle
- 【LEETCODE】141-Linked List Cycle
- 为你的Android程序选择合适的数据容器
- Python、requests模块使用代理服务器实现微博访问
- uva
- BZOJ 1038 [ZJOI 2008] 瞭望塔
- HDU 1217-Arbitrage(Floyd)
- LeetCode-141 Linked List Cycle
- 20个高级Java面试题汇总
- MyBatis使用总结
- spring 设置通过代码启动加载配置文件和设置启动顺序
- opencv 高斯混合模型提取视频或者图片的前景
- redis必杀命令:服务器
- 设计模式の工厂模式
- TCP长连接和短连接的区别
- 六、STL的数值计算---向量(数组)运算--valarray类