Use 2 pointers to traverse the sorted array. p2 moves forward 1 number each time. p1 moves forward only when find unique number.
Time Complexity : O ( len(nums) )
Space Complexity: O ( 1 ), remove duplicated number in space.
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
p1, p2 = 1, 1
last = nums[0]
while p2 < len(nums):
if nums[p2] != last:
nums[p1] = nums[p2]
last = nums[p2]
p1 += 1
p2 += 1
return p1
No comments:
Post a Comment