Two C# O(n) Solutions


  • 0
    B

    First solution with a while loop to insert zeroes at the end of the array.

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

    Second solution, without the while loop, inserts zeroes during initial pass through.

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

Log in to reply
 

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