Uses 2 pointers approach. Pointer j moves 1 step per time. Pointer 'i' moves only when encounter valid character.
Time Complexity : O ( N )
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i, j = 1, 1
count = 1
while j < len(nums):
if nums[j] == nums[j-1]:
count += 1
if count <= 2:
# keep 2 duplicate in maximum
nums[i] = nums[j]
i += 1
j += 1
else:
# skip nums[j] as there are already two duplicated numbers
j += 1
else:
count = 1
nums[i] = nums[j]
i += 1
j += 1
return i
A much simpler solution of overwritting unwanted letters.
Because it is a sorted array, we only need to compare if current letter is same to letter on last 2nd postion of the wanted array.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i = j = 2
while j < len(nums):
if nums[i-2] == nums[j]:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
return i
No comments:
Post a Comment