Time-limit-exceeded


  • 0
    C

    Hi,

    I got a time limit exceeded with input: {1, 2, 3} 1. Does anyone know what goes wrong here?

    public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if(head == null || head.next == null || n == 0)
            return head;
        int counter = 1; 
        ListNode cur =head;
        for(; cur.next != null; counter++, cur = cur.next){}
        cur.next = head;
        cur = cur.next;
        for(int i = 0; i < counter - n - 1; cur = cur.next){}
        ListNode ret = cur.next;
        ret.next = head;
        cur.next = null;
        return ret;
    }
    

    }


  • 2
    I

    here i == 0 is always true!!!!

    for(int i = 0; i < counter - n - 1; cur = cur.next){}
    

    by the way, why did you set ret.next = head?


  • 0
    C

    Oh you are right!
    I added i++ and deleted ret.next = head and then it works.


Log in to reply
 

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