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.
说实话,这道题目的描述很是不清楚,以至于我觉得很多人会觉得过oj的话只需要统计有多少个不是elem了(至少我开始这么想的)。
于是我开始写了这么一段:
class Solution2:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
l = len(A)
for i in A:
if i == elem:
l -= 1
return l
然后得到了这么一个错误:
Input: [4,5], 4
Output: [4]
Expected: [5]
纳闷了挺久,后来各种纠结才发现这个oj不光检查了返回值,连A也要一起检查,而且是检查A的前若干个是不是是满足提议的。证据如下:
AC代码:
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):
s = 0
for i in A:
if i != elem:
A[s] = i
s += 1
return s
WA代码:
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):
s = 0
l = len(A)
for i in A:
if i != elem:
A[l-s-1] = i
s += 1
return s
两份代码唯一不同的地方就是前面一个我是把满足提议的存在前面后面一个我是存在后面了。