Solution to Leetcode’s Remove Duplicates From Sorted Array II

remove duplicates from array ii
public static int removeDuplicates(int[] nums) {
//111223 => 11223
int count = 0;
int elementCount = 1;

for (int i = 0; i < nums.length; i++) {
if (i + 1 < nums.length) {

if (nums[i] == nums[i + 1] && elementCount < 3) {
elementCount++;
nums[count] = nums[i];
count++;
}else if (nums[i] == nums[i+1] && elementCount >= 3){
elementCount++;
continue;
}else if (nums[i] != nums[i+1] && elementCount >=3){
elementCount = 1;
int temp = nums[i+1];
nums[count] = temp;
nums[i+1] = -1;
count++;
}else if (nums[i] != nums[i+1] && elementCount < 3){
elementCount = 1;

if (nums[i] == -1){
nums[count] = nums[i+1];
elementCount = 3;
}

else nums[count] = nums[i];
count++;
}
}

}

return count;

}
public static int removeDuplicates(int[] nums) {
int indexCount = 2;
for (int i = 2; i < nums.length; i++) {
if (nums[i] != nums[indexCount-2]) {
nums[indexCount] = nums[i];
indexCount++;
}
}
return indexCount;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store