# Remove Element

## Question

### Problem Statement

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 in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:

Given input array nums = [3,2,2,3], val = 3

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

1. Try two pointers.
2. Did you use the property of "the order of elements can be changed"?
3. What happens when the elements to remove are rare?

## 题解1 - 两根指针从前往后遍历

### Python

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
left = 0
for num in nums:
if num != val:
nums[left] = num
left += 1

return left


### Go

func removeElement(nums []int, val int) int {
left := 0
for _, num := range nums {
if num != val {
nums[left] = num
left++
}
}

return left
}


### Java

public class Solution {
public int removeElement(int[] nums, int val) {
int left = 0;
for (int num : nums) {
if (num != val) {
nums[left++] = num;
}
}

return left;
}
}


## 题解2 - 给定值出现极少时的优化

### Python

class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
left, right = 0, len(nums)
while left < right:
if nums[left] == val:
nums[left] = nums[right - 1]
right -= 1
else:
left += 1

return right


### C++

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int right = nums.size();
for (int i = 0; i < right; i++) {
if (nums[i] == val) {
nums[i] = nums[right - 1];
right--;
i--;
}
}

return right;
}
};


### Java

public class Solution {
public int removeElement(int[] nums, int val) {
int right = nums.length;
for (int i = 0; i < right; i++) {
if (nums[i] == val) {
nums[i] = nums[right - 1];
right--;
i--;
}
}

return right;
}
}