# 27. Remove Element 移除元素

@TOC

Total Accepted: 115693 Total Submissions: 341766 Difficulty: Easy

## # 题目描述

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.
``````

## # 解题方法

### # 双指针

java版本。

``````public class Solution {
public int removeElement(int[] nums, int val) {
int tail=nums.length;
tail--;
}else{
}
}
return tail;
}
}
``````

AC:1ms

Python 版本。

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

``````class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
N = len(nums)
l, r = 0, N - 1
while l <= r:
while r >= 0 and nums[r] == val:
r -= 1
if l > r:
break
if nums[l] == val:
nums[l], nums[r] = nums[r], nums[l]
l += 1
return l
``````

### # 记录起始位置

``````class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
N = len(nums)
begin = 0
for i in range(N):
if nums[i] != val:
nums[begin] = nums[i]
begin += 1
return begin
``````

## # 日期

2016/5/3 11:29:08 2018 年 10 月 31 日 ——十月最后一天，万圣节！