[leetcode]Remove Element @ Python

1585 ワード

原題住所: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 you leave beyond the new length.
解題の構想:配列の中でelemに等しい要素を取り除いて、新しい配列の長さを返して、配列の中の要素は元の順序を維持する必要はありません.ヘッダテールポインタを使用して、ヘッダポインタがelemにぶつかると、テールポインタが指す要素と交換し、elemを配列の末尾に置き換えます.
コード:
class Solution:
    # @param    A       a list of integers
    # @param    elem    an integer, value need to be removed
    # @return an integer
    # clrs qsort
    def removeElement(self, A, elem):
        j = len(A)-1
        for i in range(len(A) - 1, -1, -1):
            if A[i] == elem:
                A[i], A[j] = A[j], A[i]
                j -= 1
        return j+1