Problem
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:
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
-
We can create two pointers, the current pointer is pointing at the end of the non-duplicated result array, the fast pointer is iterating every element of the array.
-
Initialize the current pointer at index 0, the fast pointer at index 1. If the fast pointer and current pointer have the same value, then faster pointer move forward. Else, the current pointer’s index + 1 is set to the fast pointer’s value. Iterating until the fast pointer hits the end of the array.
-
At the end, the length will be current pointer index + 1.
Solution
1 |
|