LeetCode Linked List Cycle II
来源:互联网 发布:免费宣传片制作软件 编辑:程序博客网 时间:2024/06/18 01:10
原题链接在这里:https://leetcode.com/problems/linked-list-cycle-ii/
首先找到是否有cycle,若是没有返回null。
若是有cycle,可以从head,用two pointers一个一个试直到找到cycle beginner,Time O(n^2).
另外一种方法参见了这篇帖子,是数学想法。
AC Java:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null){ return null; } ListNode walker = head; ListNode runner = head; while(runner!=null && runner.next!=null){ walker = walker.next; runner = runner.next.next; if(walker == runner){ walker = head; while(walker != runner){ walker = walker.next; runner = runner.next; } return runner; } } return null; }}
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- PHP中的一些边角料
- Cocos2d-x学习笔记之CCScene、CCLayer、CCSprite的默认坐标和默认锚点实验
- Javascript 学习
- 基础知识 -- (编程语言)
- cuDNN:利用 GPU 加速卷积神经网络
- LeetCode Linked List Cycle II
- 深度卷积神经网络CNNs的多GPU并行框架及其应用
- 卷积神经网络小结(Convolutional Neural Networks)
- 做任务的一般性原则:
- LeetCode Partition List
- 各种居中问题
- mysql备份与还原
- POJ 1032 解题报告
- 加载文档后,知道文档中有哪些“看不见的”转义字符