Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
给定一个数组和一个值,移除数组中所有该值,并返回新数组的长度。
要求时间复杂度为O(1)。
int removeElement(vector<int>& nums, int val)
{
int count = 0;
int n = nums.size();
for (int i = 0; i < n; i++) {
if (nums[i] == val) count++;
//修改原数组,去除指定数值
else nums[i - count] = nums[i];
}
return n - count;
}