Skip to content

Link to Question

EASY

Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

It does not matter what you leave beyond the returned k (hence they are underscores).

Example

Input:

nums = [3,2,2,3], val = 3

Output:

2, nums = [2,2,_,_]

Explanation:
Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).


Constraints

  • 0 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 50
  • 0 ≤ val ≤ 100

Solution: Two Pointers

  • Time Complexity: O(n)
  • Space Complexity: O(1)
C++
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int i = 0, j = -1;
        while(++j < nums.size()) {
            if (nums[j] != val) nums[i++] = nums[j];
        }
        return i;
    }
};