C++ solution to avoid unnecessary copy operations


  • 0
    D
    1. skip the nonzero entries at the begining
    2. move the following nonzero entries to their final postions, if needed
    3. set zero at the end of the array
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int cur=0, len = nums.size(), i;
            for(i=0; i<len && nums[i];++i); // step 1
            for(cur=i++; i<len;++i)  // step 2
                if(nums[i])  nums[cur++] = nums[i];
            while(cur<len) nums[cur++] = 0; // step 3
        }
    };

Log in to reply
 

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