jeudi 13 avril 2017

why my code doing overtime in OJ but run well in my computer?

I submit my code to LeetCode and it return :Time Limit Exceeded

then I debug my program using the test case which make my program over time. It can run well( not overtime) in my computer.

the problem: link:enter link description here

  1. Reorder List Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

my code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 public void reorderList(ListNode head) {
        if(head==null) return ;
        Stack<ListNode> stack=new Stack();
        ListNode cur=head;
        int length=0;
        while(cur!=null){
            stack.push(cur);
            cur=cur.next;
            length++;
        }
        if(length==2) return;
        cur=head;
        while(cur!=stack.peek()){
            ListNode tmp=cur.next;
            cur.next=stack.pop();
            cur.next.next=tmp;
            cur=tmp;
        }
    }

the test case: [1,2,3]

Aucun commentaire:

Enregistrer un commentaire