Time Limit Problem


  • 0
    K

    Could anyone help me identify the problem of my code? The OJ identified that it was time limit exceed for {3, 5}, 1,2. But when I run my code on local machine, it works? My code is as follows. The logic is to first add a mimic head node, and then break the list into three part, reverse the middle part, and link them together.

    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n || head == null)
            return head;
        
        ListNode mimic = new ListNode(-1);
        mimic.next = head;
        
        ListNode pre = mimic;
        ListNode next = mimic;
        
        for (int i = 1; i < m; i++) {
            pre = pre.next;
            next = next.next;
        }
        
        ListNode reverseCur = pre.next;
        ListNode reverseLast = reverseCur;
        ListNode reverseNext = reverseCur.next;
        ListNode reverseNextNext = reverseNext.next;
        
        next = next.next;
        for (int i = m; i < n; i++) {
            next = next.next;
            reverseNext.next = reverseCur;
            reverseCur = reverseNext;
            reverseNext = reverseNextNext;
            if (reverseNext != null)
                reverseNextNext = reverseNext.next;
        }
        next = next.next;
        pre.next = reverseCur;
        reverseLast.next = next;
        
        return mimic.next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.