Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Content:
第一次分析题目的时候出现的错误:
本题要求return 去掉重复key后的array长度
但是特别注意的是**** first length elements modified ! and doesn’t matter what values are set beyond the returned length.
Method 1: two pointers
Algorithm:
- set two pointers i, j
- i points to current position (removes the duplicate keys), j traverse the whole array
- 当J 碰到不重复的,i move to next position, 并且将j值赋给i。.
- return i + 1 (because i is index)
Code:
def removeDuplicates(nums):
if len(nums) == 0:
return 0
i = 0
for j in range(1,len(nums)):
if nums[i] != nums[j]:
i += 1
nums[i] = nums[j]
return i + 1
Method 2: counter (recode the number of duplicate keys)
Algorithm:
- set a counter c = 0 to record the number of duplicate keys
- traverse i, if nums[i]==nums[i-1], c+=1
- else: nums[i-c] = nums[i]
- return len(nums)-c
Time complexity: O(n)
Code:
def removeDuplicates(self,nums):
count = 0
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
count += 1
else:
nums[i-count] = nums[i]
return len(nums) - count