Remove Duplicates from Sorted Array II

本文介绍了一种算法,该算法可以处理已排序的数组,允许每个元素最多出现两次,并返回处理后的数组长度及修改后的数组内容。通过使用计数变量跟踪元素出现的次数,确保数组中任意元素不会超过两次重复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Remove Duplicates from Sorted Array II

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

 

标签: Array Two Pointers
分析

加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个hashmap来记录出现次数。

代码1

#include <iostream>

using namespace std;

int arr[100];

int  removetwoDuplicate(int a[],int n){
    int index = 0;
    if( n <= 2){
        index = n;
    }
    else{
        index = 2;
        for (int  i =2; i < n; i++){
            if (arr[index - 2] != arr[i]){
                arr[index] = arr[i];
                index++;
            }
        }
    }
    return index;
}


int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        cin >> arr[i];
    }
    int a = removetwoDuplicate(arr,n);
    cout << a <<endl;
    for(int i = 0; i < a; i++){
        cout << arr[i] << endl;
    }
}

代码2:

#include <iostream>

using namespace std;

int arr[100];


int main()
{
    int n;
    cin>>n;
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }
    int index = 0;
    int count = 1;
    if(n > 2 ){
       for (int j = 1; j< n; j++){
        if(arr[index] != arr[j]){
            index += 1;
            arr[index] = arr[j];
            count = 1;

        }
        else{
            count++;
            if(count <= 2){
                index++;
                arr[index] = arr[j];
            }
        }

    }

    for(int  i = 0;i <= index; i++){
        cout << arr[i];

    }
    cout << endl;
    cout << index+1<<endl;
    }
    else {
      for(int i = 0; i < n; i++){
        cout << arr[i]<< endl;
      }
      cout << n << endl;
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/superjn/p/6200525.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值