C++ solution 16ms without swapping


  • 0
    S

    Most of the solutions here are implemented using swapping. I am using number of zeros count to get the position of non-zero element in the new array. and then fill num_zero zero's in the end

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

  • 0
    L

    You can do it in one loop:

        void moveZeroes(vector<int>& nums) {
            int p=0;
            for (int i = 0; i < nums.size() || p < nums.size(); ++i) {
                if (i < nums.size() && nums[i] == 0) continue;
                else {
                    nums[p++] = (i < nums.size()) ? nums[i] : 0;
                }
            }
        }
    

Log in to reply
 

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