您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Remove Element

2008-09-13 00:43 411 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/remove-element/

题目类型:数组

难度评价:★

本文地址:/article/1377561.html

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
:
                    A[m], A
 = A
, A[m]
                    m += 1
                    n -= 1
                else:
                    n -= 1
            else:
                m += 1
        return n + 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: