leetcode || 80、Remove Duplicates from Sorted Array II

problem:

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

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

Your function should return length = 5, and A is now [1,1,2,2,3].

Hide Tags
  Array Two Pointers
题意:对数组进行去重操作,同一元素最多出现2次,返回新数组大小,同时更新数组。

thinking:

(1)先对数组排序

(2)从左往右遍历数组,出现相同元素开始计数,当重复出现次数超过2次时,用后面的元素覆盖多出的元素(数组往前移动)。

code:

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<3)
            return n;
        int i=0;
        int j=0;
        sort(A,A+n);
        while(j<n)
        {
            while(j<n&&A[j]==A[++j]); //J定位到最后一个相同元素的下一个位置
            if(j-i>2)  
            {
                int num=j-i-2;  //多余的元素的个数
                for(int k=0;k<n-j;k++) //往左移动覆盖多余的元素
                    A[i+2+k]=A[j+k];
                j=i+2;    //更新j
                n-=num;  //数组减小num
            }
            i=j;  //更新i
        }
        return n;
        
    }
};


你可能感兴趣的:(LeetCode,算法,遍历,数组去重,双指针)