algorithm-base/animation-simulation/链表篇/leetcode142环形链表2.md

156 lines
6.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [142. II](https://leetcode-cn.com/problems/linked-list-cycle-ii/)
![image-20201027175552961](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/image-20201027175552961.63sz69rbes00.png)
```java
public class Solution {
public boolean hasCycle(ListNode head) {
//特殊情况,无节点或只有一个节点的情况
if(head == null || head.next == null){
return false;
}
//设置快慢指针
ListNode pro = head.next;
ListNode last = head;
//循环条件
while( pro != null && pro.next!=null){
pro=pro.next.next;
last=last.next;
//两指针相遇
if(pro == last){
return true;
}
}
//循环结束,指针没有相遇,说明没有环。相当于快指针遍历了一遍链表
return false;
}
}
```
绿
绿2
![image-20201027180921770](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/image-20201027180921770.21fh8pt3cuv4.png)
### HashSet
HashSetHashSetHashSetHashSet
0123456**2 **2
![image-20201027182649669](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/image-20201027182649669.2g8gq4ik6xs0.png)
```java
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return head;
}
if (head.next == null) {
return head.next;
}
//创建新的HashSet,用于保存节点
HashSet<ListNode> hash = new HashSet<ListNode>();
//遍历链表
while (head != null) {
//判断哈希表中是否含有某节点,没有则保存,含有则返回该节点
if (hash.contains(head)) {
return head;
}
//不含有,则进行保存,并移动指针
hash.add(head);
head = head.next;
}
return head;
}
}
```
###
![image-20201027184755943](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/image-20201027184755943.3edot8s2xi60.png)
**a+(b+c)n+b**
b+ca线bna+(b+c)n+ba+(n+1)b+nc
**a+(b+c)m+b**,m
2,2
**a+(n+1)b+nc=2[a+(m+1)b+mc]****a+b=(n-2m)(b+c)****b+c**
a+bn-2m便n-2m1a+b=b+ca=cheada=c
1.2
2.
3.head1
![2](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/环形链表2.elwu1pw2lw0.gif)
```java
public class Solution {
public ListNode detectCycle(ListNode head) {
//快慢指针
ListNode fast = head;
ListNode low = head;
//设置循环条件
while (fast != null && fast.next != null) {
fast = fast.next.next;
low = low.next;
//相遇
if (fast == low) {
//设置一个新的指针从头节点出发慢指针速度为1所以可以使用慢指针从相遇点出发
ListNode newnode = head;
while (newnode != low) {
low = low.next;
newnode = newnode.next;
}
//在环入口相遇
return low;
}
}
return null;
}
}
```