The problem asks you to remove all instances of a specific value from an array, modifying the array in place, and return the new length of the array. The relative order of the elements may be changed. It doesn’t matter what values are set beyond the new length.
Example:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length.
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 4, 0, and 3. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
i
) iterates through the array, and the other (j
) keeps track of positions for non-target elements.j
), and j
is then incremented.j
will be the new length of the array without the specified value.#include <vector>
using namespace std;
int removeElement(vector<int>& nums, int val) {
int j = 0; // The second pointer
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != val) {
nums[j] = nums[i];
j++;
}
}
return j;
}
n
is the number of elements in the array. We are iterating through the array only once.This strategy ensures that we efficiently remove the specified value from the array while keeping the order of remaining elements arbitrary, fulfilling the in-place modification requirement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?