Move Zeroes: C#


  • 0
    M

    Here's a fairly efficient, but possibly not optimal, solution with some explanation.

        public void MoveZeroes(int[] nums) {
            
            /* The logic here is to iterate through the loop once while
             * 1) keeping a count of the number of zeros, and
             * 2) making sure that the array to the left of the current item is defragmented (contains no zeros).
             * The number of zeros removed will be re-added to the end iteration.
             */
            int noOfZeros = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] == 0)
                {
                    noOfZeros++;
                    continue;
                }
                
                // Assert(nums[i] != 0);
                
                // Copy the current item to the degragmented array to the left of the current item.
                nums[i - noOfZeros] = nums[i];
            }
            // Re-add the removed zeros.
            for (int i = 0; i < noOfZeros; i++)
            {
                nums[nums.Length - 1 - i] = 0;
            }
        }
    

Log in to reply
 

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