## 题目描述

### 英文

Given an array nums and a value val, 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.

Example 1:

``````Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.``````

Example 2:

``````Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.``````

### 中文

``````给定 nums = [3,2,2,3], val = 3,

``````给定 nums = [0,1,2,2,3,0,4,2], val = 2,

## 解法一

### 思路

1. 头指针初始指向数组第一个元素，尾指针初始指向数组最后一个元素。
2. 头指针从前往后扫描，遇到第一个`val`时停下。
3. 尾指针从后往前扫描，遇到第一个非`val`时停下。
4. 交换头尾指针所指元素。
5. 按2-4循环直到头尾指针相遇，相遇点元素下标即为新的数组长度。

``````0 1 2 2 3 0 4 2
^             ^

0 1 2 2 3 0 4 2
^       ^

0 1 4 2 3 0 2 2
^       ^

0 1 4 2 3 0 2 2
^   ^

0 1 4 0 3 2 2 2
^   ^

0 1 4 0 3 2 2 2
^
^

output: 0 1 4 0 3``````

### Python

``````class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
j = len(nums) - 1
while i <= j:
if nums[i] != val:
i += 1
elif nums[j] == val:
j -= 1
else:
nums[i], nums[j] = nums[j], nums[i]
return i``````

### Java

``````public class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int j = nums.length - 1;
while (i <= j) {
if (nums[i] != val) {
i++;
} else if (nums[j] == val) {
j--;
} else {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
return i;
}
}``````

### C++

``````class Solution {
public:
int removeElement(vector<int> &nums, int val) {
int i = 0;
int j = nums.size() - 1;
while (i <= j) {
if (nums[i] != val) {
i++;
} else if (nums[j] == val) {
j--;
} else {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
return i;
}
};``````