0026. Remove Duplicates from Sorted Array
Easy | Two Pointer | 72 ms (97.82%), 15.6 MB (96.43%)
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation:
Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation:
Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# (base case)
if len(nums) == 0 or len(nums) == 1: return len(nums)
# ==================================================
# Array + Two Pointer =
# ==================================================
# time : O(n)
# space : O(1)
moveP, placeP = 0, 0
while moveP < len(nums):
# meet number different from previous placed number
if placeP == 0 or nums[moveP] != nums[placeP - 1]:
nums[placeP] = nums[moveP]
placeP += 1
moveP += 1
return placePLast updated