## LeetCode | 27. 移除元素

27. 移除元素

``````给你一个数组 nums 和一个值 val，你需要 原地 移除所有数值等于 val 的元素，

``````

``````class Solution {
public:
int removeElement(vector<int>& nums, int val) {

vector<int>::iterator iter;

for (iter = nums.begin(); iter != nums.end(); ) {
if (*iter == val) {
nums.erase(iter); //导致迭代器失效
}
iter++;
}

return nums.size();

}
};``````

``````class Solution {
public:
int removeElement(vector<int>& nums, int val) {

vector<int>::iterator iter;

for (iter = nums.begin(); iter != nums.end(); ) {
if (*iter == val) {
iter = nums.erase(iter); //用erase方法可以返回下一个有效的iterator
}
else {
iter++;
}
}

return nums.size();

}
};``````

正确解法2：

``````class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (val != nums[fastIndex]) {
nums[slowIndex] = nums[fastIndex]; //不相等就复制过来，巧妙
slowIndex++;
}
}
return slowIndex;
}
};``````

python:

``````class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
slowIndex = 0
for fastIndex in range(0,len(nums)):  # [)
if val != nums[fastIndex]:
nums[slowIndex] = nums[fastIndex]
slowIndex = slowIndex + 1

return slowIndex``````

——————

—————————————————————

—————————————————————