LeetCode Challenge Description
Solution
We need to modify the input array, and use only $O(1)$ extra memory. With a variable cnt
to track the current count of result array, nums[cnt - 1]
is the previous value of result array, compare it with current iterated element to determine whether add it to the result array.
Time complexity: $O(N)$.
CPP version:
|
Python Solution
|
A variant challenge: Remove Duplicates from Sorted Array II
Remove Duplicates from Sorted Array II is a similar challenge, but the elements in result array can only appeared at most twice.
For this trivial different, we compare nums[i]
and nums[cnt-2]
during the loop:
|
Join my Email List for more insights, It's Free!😋