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;
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to shine in PHP coding interview

Role of AAA in 5G and the IoT Ecosystem

Learn Touch Typing

Agile supply chain strategies: Building a flexible, resilient system to respond to volatility

Type Inference by Example, Part 5

Am I the only one who has gone crazy over text editor’s themes?

Hammering nails into Kapacitor coffin

Be-aware- Before updating to Spring-boot 2.0 with flyway migration

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
Chunks

Chunks

More from Medium

Pascal’s Triangle: Arrays Question

Leetcode problem 1249: Minimum Remove to Make Valid Parentheses

LeetCode — Minimum Difficulty of a Job Schedule

Number of Islands: Leetcode — Blind 75 (Graph)