leetcode_Remove Duplicates from Sorted Array II

描述:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

思路:

直接略过重复元素

代码:

 public int removeDuplicates(int[] A) {
         if(A==null)
            return 0;
        if(A.length<3)
            return A.length;
       int len=A.length;
       int index=2;//new length
       int i=2;//to traverse the array
       int temp=0;
       while(i<len)
       {
           temp=index-2;
           while(i<len&&A[i]==A[temp])
                i++;
            if(i<len)
                A[index++]=A[i]; 
            i++;
       }
       return index;
    }


你可能感兴趣的:(remove,Duplicates)