What's wrong with this Solution? (C++)

  • 0
    class Solution {
        void moveZeroes(vector<int>& nums) {
            for (int i = 0; i < nums.size(); i++) {
               if (nums[i] == 0) {
                   nums.erase(nums.begin() + i);

    Failing on test case [0,0,1] prints [0,1,0]

  • 0

    After you erase a number, the index of elements behind that one will decrease by 1. And you still use i. So you will skip i+1 , when you erase i.

  • 0

    test case [0,0,1],when you erase the first 0,the index of elements behinds that will become 0,but in loop statement i++, then i become 1,so you pass the second 0,thus,it final prints [0,1,0].

    when you erase i, you need do i-=1,so it will judge the next elements.

Log in to reply

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