Remove Duplicates from Sorted Array II
Given a sorted array of integers where each element may appear up to twice, your task is to modify the array in-place to contain only the unique elements, preserving their original order. The function should return the new length of the modified array. This problem is a variation of the classic "Remove Duplicates" problem and tests your ability to handle constraints and optimize in-place modifications.
Problem Description
You are given a sorted integer array nums. Each element in nums can appear at most twice. Your goal is to rearrange the array nums such that it contains only unique elements, maintaining the original order of the elements. You must do this in-place, meaning you cannot allocate extra space. The function should return the new length of the modified array. The elements beyond the new length are not important and can be ignored.
Key Requirements:
- In-place modification: You must modify the input array directly. No new arrays should be created.
- Sorted input: The input array is guaranteed to be sorted in non-decreasing order.
- Maximum two occurrences: Each element appears at most twice in the original array.
- Original order: The relative order of the unique elements must be preserved.
Expected Behavior:
The function should modify the input array nums such that the first k elements (where k is the returned length) are the unique elements in their original order, with each unique element appearing at most twice. The elements beyond index k-1 are irrelevant.
Edge Cases to Consider:
- Empty array:
nums = [] - Array with a single element:
nums = [1] - Array with two elements:
nums = [1, 1] - Array with all duplicate elements:
nums = [1, 1, 1] - Array with many unique elements and some duplicates:
nums = [1, 1, 2, 2, 3, 4, 4, 5]
Examples
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5
Explanation: The modified array is [1,1,2,2,3] and the new length is 5.
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7
Explanation: The modified array is [0,0,1,1,2,3,3] and the new length is 7.
Example 3:
Input: nums = [1,2,3,4,5]
Output: 5
Explanation: The array is already unique, so the length remains 5.
Constraints
1 <= nums.length <= 10^5-10^6 <= nums[i] <= 10^6- The array
numsis sorted in non-decreasing order.
Notes
Consider using two pointers: one to track the position of the next unique element and another to iterate through the array. You'll need to keep track of how many times each element has appeared consecutively. Think about how to efficiently update the array in-place while maintaining the sorted order and respecting the maximum two occurrences constraint.