题目
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
分析
这是一道很简单的题目,对数组进行一次遍历,删除与给定值相等的关键字,返回新长度即可。
AC代码
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0 , k = 0;
while (i < nums.size())
{
if (nums[i] != val)
nums[k++] = nums[i];
i++;
}
return k;
}
};
时间: 2024-11-06 03:05:04