LeetCode算法题解(3)移除重复超过2次的重复元素

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].
紧接着上一题,同样是移除重复的元素,但是可以允许最多两次重复元素存在。
仍然是第一题的思路,但是我们需要用一个计数器来记录重复的次数,如果重复次
数大于等于2,我们会按照第一题的方式处理,如果不是重复元素了,我们将计数
器清零。

#include <iostream>
using namespace std;

int removeTwiceMore(int arr[],int n);
int main()
{
    //声明并初始化数组
   int array[]={1,1,1,2,2,3,3,3,4,4,4,4,4};
    //数组长度
    int length=sizeof(array)/sizeof(int);
    int newlength=removeTwiceMore(array,length);
    cout<<"新的数组长度为:"<<newlength;

   return 0;
}

//输入数组,数组长度,返回去重后的数组长度
//因为数组名就是地址,相当于址传递
int removeTwiceMore(int arr[],int n)
{
    int j=0;
    int num=1;
    for(int i=1;i<n;i++)
    {
        if(arr[i]==arr[j])
        {
            num++;
            if(num<=2)
            {
                arr[++j]=arr[i];
            }
        }
        else
        {
            arr[++j]=arr[i];
            num=1;
        }
    }
    return j+1;
}

输出:
新的数组长度为:8

猜你喜欢

转载自blog.csdn.net/u014571489/article/details/81192146