remove-duplicates-from-sorted-array-ii

来源:互联网 发布:卫裤网站源码 编辑:程序博客网 时间:2024/06/06 00:04

题目:

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].

程序:

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n<=2) return n;        int index=2;//允许重复两次,可以修改为三次        for(int i=2;i<n;i++)        {            if(A[i]!=A[index-2])//允许重复两次,可以修改为三次                A[index++]=A[i];        }                 return index;    }};