You are given an integer array nums and an integer val. Your task is to remove all occurrences of val from nums in-place.
After removing all occurrences of val, return the number of remaining elements, say k, such that the first k elements of nums do not contain val.
Note:
val does not matter.k positions of the array.k elements of nums must contain only elements not equal to val.Return k as the final result.
Example 1:
Input: nums = [1,1,2,3,4], val = 1
Output: [2,3,4]Explanation: You should return k = 3 as we have 3 elements which are not equal to val = 1.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: [0,1,3,0,4]Explanation: You should return k = 5 as we have 5 elements which are not equal to val = 2.
Constraints:
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100class Solution:
def removeElement(self, nums: list[int], val: int) -> int:
tmp = []
for num in nums:
if num == val:
continue
tmp.append(num)
for i in range(len(tmp)):
nums[i] = tmp[i]
return len(tmp)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 kclass Solution:
def removeElement(self, nums: list[int], val: int) -> int:
i = 0
n = len(nums)
while i < n:
if nums[i] == val:
n -= 1
nums[i] = nums[n]
else:
i += 1
return n