O(N) Solution with Explanation


  • 0
    R

    Keep track of the index containing a zero and anytime we find a non-zero element, swap it with the zero index element and then increment the zero index.

    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            if (nums.size() == 0) return;
            int zeroIndex = 0;
            for (int i = 0; i < nums.size(); i++) {
                if (nums[i] != 0) {
                    int temp = nums[i];
                    nums[i] = nums[zeroIndex];
                    nums[zeroIndex] = temp;
                    zeroIndex++;
                }
            }
        }
    };
    

Log in to reply
 

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