zoukankan      html  css  js  c++  java
  • Leetcode 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].

    典型的两指针问题

    两个指针指向初始位置,一个指针i开始遍历,记录出现相同数的个数

    如果遍历的指针i等于其前面的指针index且cnt个数超过两个,则继续移动遍历的指针

    如果遍历的指针i等于其前面的指针index且cnt个数恰好为2,则更新index指针

    如果遍历的指针不等于其前面的指针index,则出现相同的数,更新index指针,且清零计数器

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int removeDuplicates(int A[], int n){
        if(n < 3) return n;
        int index = 0, cnt = 0;
        for(int i = 1; i < n; ++ i){
            if(A[i] == A[index] && cnt < 2){
                A[++index] = A[i];
                cnt = 2;
            }else if(A[i] != A[index]){
                A[++index] = A[i];
                cnt =0 ;
            }
        }
        return index+1;
    }
    
    int main(){
        int A[] = {1,1,1,2,2,3};
        cout<<removeDuplicates(A,6)<<endl;
    }
  • 相关阅读:
    jmap之使用说明与JVM配置
    Linux之tomcat日志管理
    服务器连接数与资源监控
    Git命令之资源
    状态机
    分布式之消息系统架构
    Memcache之内存分配机制
    LRU算法
    Linux(Ubuntu)之设定开机自启动
    mysql 查询 优化
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3801225.html
Copyright © 2011-2022 走看看