[Leetcode] [Python]27:remove Element

Source: Internet
Author: User

#-*-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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.