`
bcyy
  • 浏览: 1809378 次
文章分类
社区版块
存档分类
最新评论

LeetCode Linked List Cycle II 和I 通用算法和优化算法

 
阅读更多

Linked List Cycle II

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

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

和问题一Linked List Cycle几乎一样。如果用我的之前的解法的话,可以很小修改就可以实现这道算法了。但是如果问题一用优化了的解法的话,那么就不适用于这里了。下面是我给出的解法,可以看得出,这里需要修改很小地方就可以了。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

	bool find(ListNode *head, ListNode *testpNode)
	{
		ListNode *p = head;
		while (p != testpNode->next)
		{
			if(p == testpNode)
				return false;
			p = p->next;
		}
		return true;
	}


	ListNode *detectCycle(ListNode *head) {
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.
		if(head == NULL)
			return NULL;

		ListNode *cur = head;
		while(cur != NULL)
		{
			if(find(head, cur))
				return cur->next;
			cur = cur->next;
		}
		return NULL;
	}
};


更新I的O(n)算法:

//2014-2-19 update
	bool hasCycle(ListNode *head) 
	{
		ListNode *fast = head;
		ListNode *slow = head;
		while (fast)
		{
			slow = slow->next;
			fast = fast->next;
			if (fast) fast = fast->next;
			if (fast && slow == fast) return true;
		}
		return false;
	}


现在Leetcode又更新了,第一个程序已经是Time limit exceeded了。已经更新了快指针,慢指针解法。


更新 II的O(n)算法。快指针,慢指针的解法。

//2014-2-19 update
	ListNode *detectCycle(ListNode *head)
	{
		if (!head || !head->next) return nullptr;
		ListNode *slow = head->next;
		ListNode *fast = head->next->next;
		while (fast && fast != slow)
		{
			slow = slow->next;
			fast = fast->next? fast->next->next:fast->next;
		}
		if (!fast) return nullptr;
		for (fast = head; fast != slow; fast = fast->next) slow = slow->next;
		return slow;
	}


参考这两个博客的图,和一两句话就够了。http://www.cnblogs.com/hiddenfox/p/3408931.html

http://blog.csdn.net/cs_guoxiaozhu/article/details/14209743


图:


设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。slow和fast的速度分别是qs,qf。

第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)

如果圈很小,而a很长,那么b的长度就会是绕圈几周了,但是结果也是一样成立的。

知道结论,并会推导就够了。



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics