博客域名:
http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/remove-element/
题目类型:数组
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/2920214
原题页面: https://oj.leetcode.com/problems/remove-element/
题目类型:数组
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/2920214
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
题目已经暗示可以将需要删除的元素移至数组末尾,因此用两个下标m和n,m用来从左至右遍历数组寻找该元素,n从右至左记录可以用来交换的尾部位置。
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
if None == A:
return A
len_A = len(A)
m = 0
n = len_A - 1
while m <= n:
if elem == A[m]:
if elem != A[n]:
A[m], A[n] = A[n], A[m]
m += 1
n -= 1
else:
n -= 1
else:
m += 1
return n + 1