Problem
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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:
1 |
|
Example 2:
1 |
|
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
1 |
|
Explanation
-
First, we start from the third element because we can have two duplicated, so it doesn’t matter if the first two elements are the same or not. We also use currentPointer and fastPointer technique to solve this problem. Initially, the current pointer and the fastPointer are pointing at the third element. The currentPointer is used to store the next valid element, the fastPointer is used to iterate the input array until it hits the end.
-
We can compare the fast pointer element with the currentPointer-1 index element and currentPointer-2 index element, if they are the same, then it means there are already two same elements before the currentPointer index. Else, we can set the currentPointer index’s value to the fastPointer’s pointing value.
Solution
1 |
|