JavaScript Solution, I don't know how can I make it faster, please suggest anyway to improve it


  • 0
    S

    JavaScript Solution, please feel free suggest any way to improve it, thanks.

    var deleteDuplicates = function(head) {
        if(head ==null||head.next==null) return head;
        if(head.val == head.next.val){
            head.next = head.next.next;
            deleteDuplicates(head);
        }
        else {
            deleteDuplicates(head.next);
        }
        return head
    };
    

  • 1
    F

    @superaye if there are tons of duplicates, your many recursive calls will create a big stack, which takes memory and affects performances. You could iteratively remove all duplicates of a given value before recursively moving on to the next.

    Something like this:

    var deleteDuplicates = function(head) {
        if (!head) { return head; }
        while (head.next && head.next.val === head.val) { head.next = head.next.next; }
        deleteDuplicates(head.next);
        return head;
    };
    

  • 0
    S

    @floribon Thanks for your responding, not really good at managing the memory, you reminding me paying attention to save the resource on the machine.


Log in to reply
 

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