ANYONE HELP! Why my solution failed this test case but work in custom test


  • 0
    U
    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int i = 0;
            int d = 0;
            if (nums.size() == 0) return 0;
            while (i + d < nums.size()) {
                while (nums[i + d] == val)
                    d++;
                if (i + d < nums.size())
                    nums[i] = nums[i + d];
                i++;
            }
            return nums.size() - d;
        }
    };
    

    This code failed at the test case [2,1,3,0,1,1,0,3,3,1,3] 3

    It says that my output was [2,1,0,1,1,0]

    BUT when I run my code with the input [2,1,3,0,1,1,0,3,3,1,3] 3 , my output is [2,1,0,1,1,0,1], which is correct


  • 0

    You do while (nums[i + d] == val) without checking every time that i + d is a valid index, so you get undefined behavior.


  • 0
    U

    Thank you :D


Log in to reply
 

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