C++,two pointers


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

  • 3
    A

    Similar but you can init j as zero. -1 is a little bit odd.

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

Log in to reply
 

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