# 移除数组元素()-其他

## 移除数组元素()

### 移除单个元素

``````// assume the index of the element to be removed is j
for (int i = j;i < nums.size() - 1;i ++) {
nums[i] = nums[i + 1];
}
``````

``memcpy()``
``erase()``

### 移除多个元素

**这里运用到了快慢指针。快指针的作用是遍历整个数组元素，将非目标元素传给慢指针所指的位置，遇到目标元素则跳过。慢指针的作用则是将非目标元素保存，并记录其余元素的个数。由于只用到了一次循环，因此这个算法的时间复杂度为O(n)，又因只在数组上面进行操作，只定义了两个指针，所以空间复杂度为O(1)。

``````int removeElement(vector<int>& nums, int val) {
// define a fast pointer and a slow pointer
int fastPointer = 0,slowPointer = 0;
for (;fastPointer < nums.size();fastPointer ++) {
/* if the element pointed by the fast pointer is not equal to the val,
** then let this element cover the palce pointed by the slow pointer.
** if yes,fast pointer just skip it and slow pointer do nothing.
*/
if (nums[fastPointer] != val) {
nums[slowPointer] = nums[fastPointer];
slowPointer ++;
}
}
return slowPointer;
}
``````
————————

### 移除单个元素

``````// assume the index of the element to be removed is j
for (int i = j;i < nums.size() - 1;i ++) {
nums[i] = nums[i + 1];
}
``````

``memcpy()``
``erase()``

### 移除多个元素

**这里运用到了快慢指针。快指针的作用是遍历整个数组元素，将非目标元素传给慢指针所指的位置，遇到目标元素则跳过。慢指针的作用则是将非目标元素保存，并记录其余元素的个数。由于只用到了一次循环，因此这个算法的时间复杂度为O(n)，又因只在数组上面进行操作，只定义了两个指针，所以空间复杂度为O(1)。

``````int removeElement(vector<int>& nums, int val) {
// define a fast pointer and a slow pointer
int fastPointer = 0,slowPointer = 0;
for (;fastPointer < nums.size();fastPointer ++) {
/* if the element pointed by the fast pointer is not equal to the val,
** then let this element cover the palce pointed by the slow pointer.
** if yes,fast pointer just skip it and slow pointer do nothing.
*/
if (nums[fastPointer] != val) {
nums[slowPointer] = nums[fastPointer];
slowPointer ++;
}
}
return slowPointer;
}
``````