[leetcode]Remove Duplicates from Sorted Array II

来源:互联网 发布:淘宝卖教程侵权吗 编辑:程序博客网 时间:2024/04/29 15:34
public class Solution {    public int removeDuplicates(int[] nums) {        if(nums.length==0)            return 0;        int len=1,j=1,time=1,temp=nums[0];        for(int i=1;i<nums.length;i++){            if(temp == nums[i]){                if(++time==2){                    nums[j++]=nums[i];                    continue;                }                else if(time>2){                    while(++i<nums.length && nums[i]==temp);                }            }            if(i<nums.length)                nums[j++]=nums[i];             time=1;             temp=nums[j-1];        }        return j;    }}

快慢指针,把出现次数大于2的数字,直接使用后面的覆盖掉。最后j就是数组的长度。

只需要特殊处理time==2的时候,和大于2的时候一定要在后面找一个不同的数字覆盖掉当前的

找的时候还要注意有没有达到数组的末尾。

0 0