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;
    }
  • 相关阅读:
    MongoDB简单使用
    mongodb安装部署
    分布式通信-序列化
    分布式通信协议
    分布式概念
    springboot-事件
    spring-事件
    spring-@Component/@ComponentScan注解
    springboot-Date日期时间问题
    enginx:基于openresty,一个前后端统一,生态共享的webstack实现
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3801225.html
Copyright © 2011-2022 走看看