Playing Hacks and Stuffs!
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:
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
.k
.I just solved this using array method pop()
My solve script is in the below link
Solve Script: link
Another efficient way to solve this is using Two Pointer
def removeElement(nums, val):
index = 0
for i in range(len(nums)):
if nums[i] != val:
nums[index] = nums[i]
index += 1
return index
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
while i < len(nums):
if nums[i] == val:
nums.pop(i)
else:
i += 1
return len(nums)