LeetCode Hot 热题100 算法题 142.环形链表II-算法&测试-medium模式

LeetCode Hot 热题100 算法题 142.环形链表II-算法&测试-medium模式

给定一个链表,返回聊表开始入环到达第一个节点。如果链表无环则返回null。
说明:不允许修改给定的链表。
进阶:你是否可以使用O(1)空间解决此题?

package leetcode.medium;

import java.util.HashSet;
import java.util.Set;

//142.环形链表II
public class Solution142 {
	public static void main(String[] args) {
		ListNode head = new ListNode(3);
		head.next=new ListNode(2);
		head.next.next=new ListNode(0);
		head.next.next.next=new ListNode(-4);
		head.next.next.next.next=head.next;
		
		S142CircularList testCircularList = new S142CircularList();
		ListNode start = testCircularList.detectCycle(head);
		if (start==null) {
			System.out.println("not found");
		}else {
			System.out.println(start.val);
		}
	}
}

class S142CircularList{
	//法1:需额外空间
	public ListNode findCircu(ListNode head) {
		Set<Integer> hashSet = new HashSet<Integer>();
		ListNode cur = head;
		while(cur!=null) {
//			if (hashSet.contains(cur.val)) {
//				return cur;
//			}
//			hashSet.add(cur.val);
			if (!hashSet.add(cur.val)) {
				return cur;
			}
			cur=cur.next;
		}
		return null;
	}
	
	//法2:快慢指针 空间复杂度O(1)
	//快慢指针同时从head出发,只要链表存在环,fast和slow就会在环内某点相遇
	//相遇时,让ptr指针从head出发,当ptr与slow相遇时 即到达环开始的节点
	public ListNode detectCycle(ListNode head) {
		ListNode fast = head;
		ListNode slow = head;
		do {
			if (head==null || head.next==null) {
				return null;
			}
			slow=slow.next;
			fast=fast.next.next;
		} while (fast!=slow);
		
		ListNode ptr = head;
		do {
			ptr=ptr.next;
			slow=slow.next;
		} while (ptr!=slow);
		return ptr;
	}	
}

参考:

  1. https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode-solution
  2. https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值