I'm trying to write a program for a given array and a value, to remove all instances of that value in place and return the new length.
Example: Given input array nums = [3,2,2,3], val = 3
It should return length = 2, with the first two elements of nums being 2.
Here is my code:
Code 1:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
j = len(nums) - 1
while i <= j:
while i <= j and nums[j] != val:
j -= 1
while i <= j and nums[i] == val:
i += 1
if i <= j:
nums[i], nums[j] = nums[j], nums[i]
return len(nums[i:])
This returns the array slice in reverse order.
Input:
[3,2,2,3]
3
Output: [3,3]
Expected: [2,2]
However, if I make slight modifications at the end of the code 1, it gives me the correct output:
nums[:] = nums[i:]
return len(nums[i:])
Code 2:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
j = len(nums) - 1
while i <= j:
while i <= j and nums[j] != val:
j -= 1
while i <= j and nums[i] == val:
i += 1
if i <= j:
nums[i], nums[j] = nums[j], nums[i]
nums[:] = nums[i:]
return len(nums)
I cant figure out why my code 1 doesnt work. Could someone help me understand why slice doesnt work as expected?