LeetCode-142. Linked List Cycle II

来源:互联网 发布:创可贴的网络意思 编辑:程序博客网 时间:2024/05/29 04:45

142

Linked List Cycle II

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?

一看这题,呵呵,这不就是前面那道题改一下返回值么。
后来一想,不对,如果用fast-slow-runner那个方法的话,找到的时候不一定是开头。
那么,用我一开始自己想的那个o(N^2)的方法总可以吧。
于是,用那个代码改了一下return,然后submit

/** * 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) {        ListNode nowNode=head;        while((nowNode!=null)&&(nowNode.next!=null)){            if(nowNode.next==nowNode){                return nowNode;            }            ListNode innerNowNode=head;            while(innerNowNode.next!=null){                if(nowNode==innerNowNode){                    break;                }                if(nowNode.next==innerNowNode){                    return nowNode.next;                }                innerNowNode=innerNowNode.next;            }            nowNode=nowNode.next;        }        return null;    }}

不出我所料,也是前面的正确性测试通过了,后面大量数据的时候TLE了,呵呵。
现在看来,只能想想能不能改改fast-slow-runner那个方法了。

0 0