[leetcode]Remove Element @ Python


原題地址: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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM