Python solution - O(n) 60ms


  • 0
    G
    class Solution:
        # @param    A       a list of integers
        # @param    elem    an integer, value need to be removed
        # @return an integer
        # 1:52
        def removeElement(self, A, elem):
            tail = 0
            for i in range(len(A)):
              if A[i] != elem:
                  A[tail] = A[i]
                  tail += 1
    
            return tail

  • 0
    R
    class Solution:
        # @param {integer[]} nums
        # @param {integer} val
        # @return {integer}
        def removeElement(self, nums, val):
            i = 0;
            length = len(nums)
            while i < length:
                if nums[i] == val: del nums[i]; length -= 1; continue
                i += 1
            return length

  • 0

    Looks like Google doesn't know Python. Strange, I thought they used it a lot.

    def removeElement(self, A, elem):
        tail = 0
        for a in A:
            if a != val:
                A[tail] = a
                tail += 1
        return tail

  • 0
    G

    We primary use Java and C++ here :p (well, good catch anyway (thumbsup))


  • 0
    G

    hmmm, I think each del in Python array is an O(n) operation.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.