Simple Javascript solution with filter


  • 0
    A
    const moveZeroes = (nums) => {
      const zeroes = nums.filter(x => x === 0);
      const newNums = nums.filter(x => x !== 0).concat(zeroes);
      nums.length = 0;
      nums.push(...newNums);
    }
    

  • 0

    @akccakccwww simple yes, but not optimal. Try to do this in place.


  • 0
    A

    @jdrogin

    Thanks for your reply, I try to edit my function below, is it "in place" now?

    const moveZeroes = (nums) => {
      nums.splice(0, nums.length, ...nums.filter(x => x !== 0).concat(nums.filter(x => x === 0)));
    }
    

  • 0

    @akccakccwww well I'm not familiar with how javascript will handle this but I would think when you do the filter it is creating the result in a new array, which is not in place. For in place you want to deal with the array directly. Here is my solution in C#

        public void MoveZeroes(int[] nums) 
        {
            int nonZeroCount = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] != 0)
                {
                    nums[nonZeroCount] = nums[i];
                    nonZeroCount++;
                }
            }
            
            for (int i = nonZeroCount; i < nums.Length; i++)
            {
                nums[i] = 0;
            }
        }
    

  • 0
    A

    @jdrogin okay, I just want to achieve it with a functional way( I'm learning functional programming).

    But I think it is impossible to be in place without for loops in Javascript, anyway thank you.


Log in to reply
 

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