Four-line, easy-to-understand Python solution


  • 0
    D
    class Solution(object):
        def removeElement(self, nums, val):
            """
            :type nums: List[int]
            :type val: int
            :rtype: int
            """
            for i in xrange(len(nums)-1, -1, -1):
                if nums[i] == val:
                    nums.pop(i)
            return len(nums)

  • 0

    What's the point of gathering all bad indexes before the popping?


  • 0
    D

    @StefanPochmann If you mean "Why don't you just pop as you go," in my experience, popping from a list while iterating over it is problematic. If you mean "Why not just use the remove method," I chose not to do that because it's O(n), so if all of the values to be deleted are at the end of the list, the performance is bad. I'd be happy to learn if you have a better suggestion, or if you think these reasons are not good.


  • 0

    "in my experience, popping from a list while iterating over it is problematic"

    Not if you go backwards like you're already doing.

    "I chose not to [use the remove method] because it's O(n)"

    The pop method is also only O(n).

    But what I meant was "pop as you go". I think it's quite a bit better.


  • 0
    D

    "The pop method is also O(n)."
    Ah, right. I was thinking only about (constant time) access, not the shifting.

    I'm editing the function. Thanks for your input!


Log in to reply
 

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