Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements k; the first k elements of nums must hold the unique elements in order.
Example 1
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: First two elements become the unique values 1 and 2.
Example 2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: 5 unique elements written to the front.
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100nums is sorted in non-decreasing orderThis is a two-pointer problem where both pointers move through the same array, not toward each other.
One pointer (slow) marks where the next unique value should be written; another (fast) scans ahead looking for it.
Because the array is sorted, duplicates are always adjacent — you never need to look further than the last written value.
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int slow = 0;
for (int fast = 1; fast < nums.length; fast++) {
if (nums[fast] != nums[slow]) {
slow++;
nums[slow] = nums[fast];
}
}
return slow + 1;
}Time: O(n) · Space: O(1)