I don't understand how work output in my case. Could you explain to me what I'm doing wrong?
task:(27. Remove Element)
Given an integer array
numsand an integerval, remove all occurrences ofvalinnumsin-place. The order of the elements may be changed. Then return the number of elements innumswhich are not equal toval.Consider the number of elements in
numswhich are not equal tovalbek, to get accepted, you need to do the following things:
Change the array
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important as well as the size ofnums.Return
k.
My solution:
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if len(nums) > 1:
nums = [u for u in nums if u != val]
print("nums = ", nums)
if val not in nums:
return len(nums)
Testcase:
nums =[0,1,2,2,3,0,4,2]
val = 2
Results:
Stdout (print in loop): nums = [0, 1, 3, 0, 4]
Output: [0,1,2,2,3]
Expected: [0,1,4,0,3]
The problem is that you are not removing the elements in-place, so nums outside the function is not affected.
One option is to iterate over the list and remove items with pop. To avoid index out of range exception iterate over the list from end to start
for i in range(len(nums) - 1, 0, -1):
if nums[i] == val:
nums.pop(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With