Resposta de referência
Given an integer sorted array in increasing order, remove duplicates so each unique element appears only once. Because Python lists don't change length in-place for this problem, place the results in the first k positions of the same array and return k (the new length). Only the first k elements are valid after the call; elements beyond k are stale.
Image from LeetCode
Example 1: input array is [1,1,2,2], the function should return 2.
Example 2: input array is [1,1,2,3,3], the function should return 3.
Solution:
- Run a loop from index 1 to the end. Compare the current element with the previous unique element; when different, write it at insertIndex and increment insertIndex. Return insertIndex.
- Return insertIndex as it is the k.
This question is relatively straightforward once you know how. If you put more time into understanding the statement, you can easily come up with a solution.
def removeDuplicates(array):
size = len(array)
if size == 0:
return 0
insertIndex = 1
for i in range(1, size):
if array[i - 1] != array[i]:
array[insertIndex] = array[i]
insertIndex += 1
return insertIndex
array_1 = [1, 2, 2, 3, 3, 4]
k1 = removeDuplicates(array_1)
# 4; array_1[:k1] -> [1, 2, 3, 4]
array_2 = [1, 1, 3, 4, 5, 6, 6]
k2 = removeDuplicates(array_2)
# 5; array_2[:k2] -> [1, 3, 4, 5, 6]