My python solutions


  • 0
    Y

    Solution1: Two pointers - Do not change the relative orders - 46ms

    class Solution(object):
        def removeElement(self, nums, val):
            i, j = 0, 0
            while i < len(nums):
                if nums[i] != val:
                    nums[i], nums[j] = nums[j], nums[i]
                    j += 1
                i += 1
            return len(nums[0:j])
    

    Solution2: 39ms

    class Solution(object):
        def removeElement(self, nums, val):
            i, j = 0, len(nums)
            while i < j:
                if nums[i] == val:
                    j -= 1
                    while nums[j] == val and i < j:
                        j -= 1
                    nums[i], nums[j] = nums[j], nums[i]
                    if i == j:
                        return len(nums[:i])
                i += 1
            return len(nums[:i])
    

    Solution3: 52ms

    class Solution(object):
        def removeElement(self, nums, val):
            i = 0
            while True:
                try:
                    nums.remove(val)
                except ValueError:
                    return len(nums)
    

Log in to reply
 

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