LeetCode 27.Remove Element

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for (vector<int>::iterator iter = nums.begin(); iter != nums.end();) {
if (*iter == val) {
iter = nums.erase(iter);
}
else {
iter++;
}
}
return nums.size();
}
};
int main() {
Solution s;
vector<int> nums;
int n;
cin >> n;
int t;
for (int i = 0; i < n; i++) {
cin >> t;
nums.push_back(t);
}
int val;
cin >> val;
cout << s.removeElement(nums, val) << endl;
return 0;
}
------本文结束感谢阅读------