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 in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
My code:
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = nums.count(val)
for i in range(k):
nums.remove(val)
return len(nums)
The objective is to remove all occurrences of the element 'val' from the list 'nums' in-place and return the count of elements in 'nums' that are not equal to 'val'.
First, I thought about how to remove all occurrance of the element(val). I used count() to get the number of occurrance of the val. And I used remove() using for loop to remove all val.I then return the length of nums.
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for i in range(len(nums):
if nums[i] != val:
nums[k] = nums[i]
k += 1
return k