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.
1def removeDuplicates(nums):
2 if len(nums) <= 2:
3 return len(nums)
4
5 write = 2
6
7 for read in range(2, len(nums)):
8 if nums[read] != nums[write - 2]:
9 nums[write] = nums[read]
10 write += 1
11
12 return write
13
This Python solution uses two pointers: 'write' initialized at position 2 and 'read' iterating from 2 to the end of the array. The condition nums[read] != nums[write - 2]
ensures that we only allow two instances of each element.
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).
1public int RemoveDuplicates(int[] nums) {
2 if (nums.Length <= 2) return nums.Length;
3
4 int write = 1, count = 1;
5 for (int read = 1; read < nums.Length; read++) {
if (nums[read] == nums[read - 1]) {
count++;
} else {
count = 1;
}
if (count <= 2) {
nums[write++] = nums[read];
}
}
return write;
}
The C# solution operates similarly by using a count variable. By comparing consecutive elements and managing a write pointer, it effectively limits the appearances to two per unique element.