Sponsored
Sponsored
This approach uses the two-pointer technique to traverse the array and modify it in-place. The 'write' pointer tracks where the next unique element should be written, ensuring each appears at most twice. The 'read' pointer goes through the array, checking each element.
Time Complexity: O(n), Space Complexity: O(1), where n is the length of the input array.
1public int removeDuplicates(int[] nums) {
2 if (nums.length <= 2) return nums.length;
3
4 int write = 2;
5 for (int read = 2; read < nums.length; read++) {
6 if (nums[read] != nums[write - 2]) {
7 nums[write] = nums[read];
8 write++;
9 }
10 }
11 return write;
12}
The Java implementation uses the same logic, iterating through the array with a 'read' pointer and modifying it in place using a 'write' pointer to ensure at most two occurrences of each number.
This approach utilizes a variable to track the count of each duplicate as we iterate through the sorted array. The array is overwritten by resetting the duplicate counter each time a new element is found.
Time Complexity: O(n), Space Complexity: O(1).
1int removeDuplicates(int* nums, int numsSize)
The C solution uses a count variable to keep track of consecutive duplicates. For each element checked, the count is updated, and elements are copied based on whether they meet the condition of appearing at most twice.