C# O(N) simple and readable

  • 0
    public class Solution 
        public void MoveZeroes(int[] nums)
            // number of nonzeros moved
            var numsMoved = 0;
            for (var i = 0; i < nums.Length; ++i)
                if (nums[i] == 0) continue;
                // no need to swap element with itself
                if (numsMoved != i)
                    // move nonzero into position
                    var hand = nums[numsMoved];
                    nums[numsMoved] = nums[i];
                    nums[i] = hand;                          
                // smaller than i by exactly the number of 0s seen

    This solution is based on the observation that it is much easier to move NZ (non-zero) numbers forward, while maintaining order, than it is to move zeros back. The first NZ will always go to position 0, the second to position 1, and so on. Therefore, if you simply swap the NZ with its proper element, in order, you have solved the problem. In order is important; it insures you never swap a NZ with another NZ.

Log in to reply

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