题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
问题要求在O(1)的空间复杂度下完成该算法,也就是in-place。很显然是用双指针,i指针表示数组有效范围,j指针是一个遍历指针,每次遍历到一个第一次出现的数时,用一个计数器进行计数,第一次第二次出现的数就直接往i位置上复制,第三次或以上出现的就直接将j后移不复制到位置i上,注意这里是i先自加再移位。代码如下:
class Solution {
public int removeDuplicates(int[] nums) {
int i=0,j=0;
while(j<nums.length-1)
{
int count=1;
while(j<nums.length-1 && nums[j+1]==nums[j])
{
count++;
if(count<=2)
nums[++i]=nums[++j];
else
j++;
}
if(j<nums.length-1)
nums[++i]=nums[++j];
}
return i+1;
}
}