""" Here's an ordered array nums , Please delete the repeated elements in place , Make each element appear only once , Returns the new length of the deleted array . Don't use extra array space , You have to modify the input array in place And using O(1) Complete with extra space . """
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
i = 0
while i < len(nums):
if len(nums)==1:
break
if nums[i]==nums[i-1]:# Remove duplicate elements from the original array
del nums[i]
else:
i += 1
return len(nums)
fast The pointer is used to scan ,slow The pointer is used to point to the position of the answer
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
fast = slow = 1 #fast The pointer is used to scan ,slow The pointer is used to point to the position of the answer
while fast < n:
if nums[fast] != nums[fast - 1]: # When no duplicates are found , take fast Copy location to slow
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
nums = [0,0,1,1,2]
S = Solution()
result = S.removeDuplicates(nums)
print(result)
hello , Hello everyone . Today
introduction Previous article