LeetCode 27.Remove Element
Description:
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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
分析:
太简单的一道题,可以采用vector的erase方法,遍历循环一次,将数组中与val相等的数erase掉,直接返回数组的大小即可。
注意erase方法不要出现野指针的问题。
vector标准库函数erase的声明:iterator erase (const_iterator position);
,注意到形参和返回值都是迭代器。
代码如下:
1 |
|