One line C++


  • 1

    One line.

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

    3 lines.

    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int j = 0;
            for(auto x: nums) if(x) nums[j++] = x;
            while(j < nums.size()) nums[j++] = 0;
        }
    };
    

Log in to reply
 

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