what's wrong with my javascript code?


  • 0
    L

    my code:

    var removeDuplicates = function (nums) {
        var n = [];
        var t = null;
        for (var i = 0; i < nums.length; i++)
            if (t !== nums[i]) {
                n.push(nums[i]);
                t = nums[i];
            }
        return n;
    };
    

    then the Submission Result is:

    Wrong Answer
    Input:
    [1,2]
    Output:
    []
    Expected:
    [1,2]
    

  • 0
    X

    Do not allocate extra space for another array, you must do this in place with constant memory.


  • 0
    X
    var removeDuplicates = function(nums) {
        if(nums.length === 0) {
            return 0;
        }
        
        var new_tail = 0;
        for(var i = 1; i < nums.length; i++) {
            if(nums[i] != nums[new_tail]) {
                new_tail++;
                nums[new_tail] = nums[i];
            }
        }
        
        return new_tail + 1;
    };
    

Log in to reply
 

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