Javascript code, Output Limited Exceed, why?


  • 1
    S
    var removeDuplicates = function(A) {
        if(A.length == 0){
            return 0;
        }
        var i = 1;
        var temp = A[0];
        while(A[i]){
            if(A[i] === temp){
                A.splice(i,1);
            }
            else{
                temp = A[i];
                i++;
            }
        }
        return A.length;
    };

  • 0
    V

    Possibly splice method is the culprit. Every time you are removing an element in the array, it's not necessary.

    You can just modify the value at that index and return number of unique elements.

    ...
    temp = 0;
    if (A[i] != temp) A[++temp] = A[i++];
    ....

Log in to reply
 

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