DEV Community

schudy
schudy

Posted on

LeetCode 80. Remove Duplicates from Sorted Array II

I used 2 pointers just the same as Problem 26. These problems are quite similar, the only difference is for 80, one number can appear at most 2 times.

The algorithm is the pointer i is slow, to mark the invalid elements that need to be replaced; j is faster to traverse the list.

Since every number can appear twice, so i and j will start from the third number. If the nums[j] is not the same as its previous two numbers at the same time, then it is a valid number. Then i and j will move to the next. Else i won't move and wait for j to find a valid number to replace i. The final i is the value that need to be returned.
Alt Text

Top comments (0)