O(n) simple solution for Python

  • 0
    def removeElement(nums, val):
        i = 0
        while i < len(nums):
            if nums[i] == val:
                nums[i], nums[-1] = nums[-1], nums[i]
                i += 1
        return len(nums)

    Compare the elements from begining of the list and switch it to the end, then use list.pop() to remove it.
    The edited array nums can also be returned if you want.

Log in to reply

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