Loading
Leetcode / 27. Remove Element

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution
{
    // time O(n)
    // space O(1)
    int removeElement(int[] nums, int val)
    {
        int k = nums.length;
        for (int i = 0; i < k; )
        {
            if (nums[i] == val)
            {
                nums[i] = nums[k - 1];
                k--;
            }
            else
            {
                i++;
            }
        }

        return k;
    }

   void test()
    {
        int[] testdata1 = {3, 2, 2, 3};
        int testcase1 = removeElement(testdata1, 3);
        assert testcase1 == 2;
        assert testdata1[0] == 2;
        assert testdata1[1] == 2;

        int[] testdata2 = {0, 1, 2, 2, 3, 0, 4, 2};
        int testcase2 = removeElement(testdata1, 2);
        assert testcase2 == 5;
        assert testdata2[0] == 0;
        assert testdata2[1] == 1;
        assert testdata2[2] == 4;
        assert testdata2[3] == 0;
        assert testdata2[4] == 3;

        int[] testdata3 = {};
        int testcase3 = removeElement(testdata3, 0);
        assert testcase3 == 0;
    }

    public static void main(String[] args)
    {
        (new Solution()).test();
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: