0026. Remove Duplicates from Sorted Array - chasel2361/leetcode GitHub Wiki
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2: Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
這題的限制在於必須在原本的list裡面刪除重複值,不能建立新的list來裝。
[1] 如果 nums 不存在的話就傳零出去
[2] 檢查的是當前項以及次項,所以檢查至倒數第二項即可
[3] 刪去當前項後,為了將順序停在原項需要先退一項
[4] 前進一項
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: # [1]
return 0
i = 0
while i < len(nums) - 1: # [2]
if nums[i] == nums[i + 1]:
del nums[i]
i -= 1 # [3]
i += 1 # [4]
return len(nums)
這樣的時間複雜度是 O(N) ,空間複雜度是O(1)
這題很怪,題目明明要求要刪除,結果丟上去比較快的解法都沒刪除,偷吃步喔XD