#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
27:remove Element
https://oj.leetcode.com/problems/remove-element/
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 are you leave beyond the new length.
===comments by dabay===
One loop, two pointers, one pointing to the insertion position, the other one going straight ahead.
If number second is the number that needs to be deleted, the pointer of number second continues.
If it is not the number to be deleted, move the number of pointer second to the position of a pointer, and the two pointers continue to go.
Finally with the new array, returns the length.
‘‘‘
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):
i = j = 0
While J < Len (A):
If A[J]! = Elem:
A[i] = A[j]
i + = 1
J + = 1
A = a[:i]
Return Len (A)
def main ():
Sol = solution ()
Print sol.removeelement ([1,1,2], 1)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]27:remove Element