leetcode 142. Linked List Cycle II
2016-06-19 11:23
246 查看
题目描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
解题思路:(注意:严格来说,图论中圈和环还是有很大的区别。。环是指存在自己指向自己的边,所以这里用圈而不是环)
利用快慢两个指针就可以解决,虽说有点技巧性,但该题还是很常见的:
慢指针每次走1步,快指针每次走2步,如果遇见了null,表明不存在圈,否则:
在第一次相遇的时候,慢指正走了N + K步,其中N表示从起点走到圈的起始点,而快指针走了2*(N+K)步,所以 2*(N+K) - (N+K) = N+K,
设圈的长度为L, 则N+K = t * L,其中t为整数,而由慢指针也可以看到此时位于圈起始点的L处,也就是说再走N步就可以达到圈的起始点,
所以这时只需要让慢指针从起始点出发,快指针从原地出发,速度都是1,则慢指针走到圈的起始点,恰好走了N步,所以快指针也恰好走了N步,也就是到达了圈的起始点,
即再次相遇的地点就是圈的起始点。
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
解题思路:(注意:严格来说,图论中圈和环还是有很大的区别。。环是指存在自己指向自己的边,所以这里用圈而不是环)
利用快慢两个指针就可以解决,虽说有点技巧性,但该题还是很常见的:
慢指针每次走1步,快指针每次走2步,如果遇见了null,表明不存在圈,否则:
在第一次相遇的时候,慢指正走了N + K步,其中N表示从起点走到圈的起始点,而快指针走了2*(N+K)步,所以 2*(N+K) - (N+K) = N+K,
设圈的长度为L, 则N+K = t * L,其中t为整数,而由慢指针也可以看到此时位于圈起始点的L处,也就是说再走N步就可以达到圈的起始点,
所以这时只需要让慢指针从起始点出发,快指针从原地出发,速度都是1,则慢指针走到圈的起始点,恰好走了N步,所以快指针也恰好走了N步,也就是到达了圈的起始点,
即再次相遇的地点就是圈的起始点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { if(head == 0 || head -> next == 0) return 0; ListNode *fast = head -> next -> next, *slow = head -> next; while(fast != slow){ if(fast == 0 || fast -> next == 0) return 0; slow = slow -> next; fast = fast -> next -> next; } slow = head; while(fast != slow){ fast = fast -> next; slow = slow -> next; } return slow; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解