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 firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).
My solution is using two pointers, but seems it doesn’t need to care about the elements in the list.
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
start_pointer = 0
end_pointer = len(nums) - 1
occurrence = 0
while end_pointer >= start_pointer:
if nums[end_pointer] == val:
nums[end_pointer] = "_"
end_pointer -= 1
occurrence += 1
elif nums[start_pointer] == val:
nums[start_pointer] = nums[end_pointer]
nums[end_pointer] = "_"
end_pointer -= 1
start_pointer += 1
occurrence += 1
else:
start_pointer += 1
return len(nums) - occurrence
Others like below
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
rem = 0
for i in range(len(nums)):
if(nums[i] != val):
nums[rem] = nums[i]
rem += 1
return rem
搶先發佈留言