My Straightforward Python Solution


  • 0
    W
    class Solution:
    # @param {integer[]} nums
    # @param {integer} val
    # @return {integer}
    def removeElement(self, nums, val):
        if nums == []:
            return 0
        else:
            new = len(nums)
            count = 0
            for i in range(0, len(nums)):
                if nums[i] == val:
                    j = new - 1
                    while nums[j] == val and j > i:
                        new -= 1
                        j = new - 1
                    nums[i] = nums[j]
                    new -= 1
                    count += 1
            return len(nums) - count
    

    *Note: Once an element == val, it will be replaced by the last element that is not equal to val (which is nums[new]). Hope it to be understandable!
    Run time: 44ms


Log in to reply
 

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