DEV Community

睡觉
睡觉

Posted on

Remove Element (Easy) | LeetCodePractice #8

Remove Element (LeetCode 27)

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements k in nums which are not equal to val.

Python

####Pop Elements (Runtime: 0ms, Memory: 12.5MB)
    #DECLARE nums: ARRAY of INTEGER
    #DECLARE val: INTEGER
class Solution(object):
    def removeElement(self, nums, val):
        i = 0
        while i < len(nums):
            if nums[i] == val:
                nums.pop(i)
            else:
                i += 1
        return len(nums)



####Insert to Head (Runtime: 0ms, Memory: 12.4MB)
    #DECLARE nums: ARRAY of INTEGER
    #DECLARE val: INTEGER
class Solution(object):
    def removeElement(self, nums, val):
        head_index = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[head_index] = nums[i]
                head_index += 1
        return head_index
Enter fullscreen mode Exit fullscreen mode

Thoughts

This is basically copy and paste from LeetCode 26!!! Bruh...

Top comments (0)