Remove Duplicatesfrom Sorted Array I I Algorithm
The Remove Duplicates from Sorted Array II algorithm is a modified version of the classic problem of removing duplicates from a sorted array. This algorithm aims to remove the duplicates in a sorted array in such a way that each element appears at most twice, instead of just once as in the original problem. The objective is to do this in-place, i.e., without using any additional memory, and maintain the relative order of the elements. This problem can be efficiently solved using a two-pointer approach, where one pointer iterates through the array, while the other pointer keeps track of the position to insert the next unique element.
The algorithm starts by initializing two pointers, 'i' and 'j', where 'i' represents the position of the next unique element and 'j' iterates through the array. It also initializes a count variable to keep track of the occurrences of the current element. As 'j' iterates through the array, the algorithm checks if the current element is the same as the previous element. If it is, the count variable is incremented. If the count is less than or equal to 2, this means the element can still be part of the final array, and thus, the algorithm assigns the value at index 'j' to index 'i', and increments 'i'. If the current element is different from the previous element, the count variable is reset to 1, and the process continues. Once the iteration is completed, the final length of the modified array is equal to the value of 'i'. In this way, the algorithm effectively removes duplicates while ensuring each element appears at most twice in the sorted array.
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 0) return 0;
int low = 0, high;
int count = 1;
for (high = 1; high < n; high++) {
if (A[low] == A[high]) {
if (count < 2) {
count += 1;
A[++low] = A[high];
}
}
else {
A[++low] = A[high];
count = 1;
}
}
return low + 1;
}
};