[LeetCode] Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

这题类似于检测环路,关键是求得环的长度。自己想出了一个O(n))的快慢指针解法,该解法需要让两个指针一共相遇3次。


1) 先检测是否存在环,如果存在,那么快慢指针相遇地点比为环内。

2) 如果存在环,那么让其中任意一个指针再往下继续走,而另一个指针不动,直到两指针再次相遇。可以知道其中一个指针走的距离是环的长度,标记为L。

3) 让两个指针同时回到表头,并且让一个指针先走L长度,使得两指针的间距为L。然后让两指针同速走直到相遇。相遇地点即为所求的环的起始节点。

	public ListNode detectCycle(ListNode head) {
		ListNode slow = head, fast = head;

		// 1st Meet: find the meeting point
		while (fast != null && fast.next != null) {
			slow = slow.next;
			fast = fast.next.next;
			if (slow == fast)
				break;
		}
		// error check - no meeting point
		if (fast == null || fast.next == null)
			return null;

		// 2nd Meet: calculate the length of the cycle
		int cycleLen = 0;
		do {
			slow = slow.next;
			cycleLen++;
		} while (slow != fast);

		// 3rd Meet: find the beginning
		slow = fast = head;
		for (int i = 0; i < cycleLen; i++) {
			fast = fast.next;
		}
		while (fast != slow) {
			fast = fast.next;
			slow = slow.next;
		}

		return fast;
	}

在网上搜了下,发现的确有更精简的O(n)解法,只需要让指针相遇两次,但对推理能力要求更高。

http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/
区别在于,当快慢指针指在同一节点相遇后,将其中一个指针指向表头,然后两个指针再同速后移,两个指针再次相遇的地方就是环的起始处。这个结论要推出来还是很有一定难度的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值