zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted Array II

    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;
    }
  • 相关阅读:
    带参数的装饰器
    python清空文件夹
    sqlalchemy的filter使用
    git pull命令的用法
    通过jenkins打包ipa包报错:Command CodeSign failed with a nonzero exit code(errSecInternalComponent)
    postman上传图片,及接口上传图片
    liunx中crontab没有生效
    liunx正则危险符号“*”星号
    rqalpha的改造工作
    Qt浅谈之一:内存泄露(总结)
  • 原文地址:https://www.cnblogs.com/superjn/p/6200525.html
Copyright © 2011-2022 走看看