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

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

    Solution:

     1     int removeDuplicates(int A[], int n) {
     2         if(n <= 2)
     3             return n;
     4         int pre = A[0];
     5         int same_count = 0;
     6         int rm_count = 0;
     7         int i = 1;
     8         while(i < n - rm_count) {
     9             if(A[i] == pre){
    10                 same_count ++;
    11             }else{
    12                 pre = A[i];
    13                 same_count  = 0;
    14             }
    15             
    16             if(same_count >= 2){
    17                 //remove A[i]
    18                 for(int j = i + 1; j < n - rm_count; j ++)
    19                     A[j - 1] = A[j];
    20                 rm_count ++;
    21             }else{
    22                 i ++;
    23             }
    24         }
    25         return n - rm_count;
    26     }
  • 相关阅读:
    JS 笔记
    html笔记 横向两列布局
    jsp HTTP Status 405
    有效范围为request的bean
    jsp:session对象存储数据
    sql笔记
    StringBuffer的用法
    VB学习笔记
    html 笔记
    Linux 笔记
  • 原文地址:https://www.cnblogs.com/guyufei/p/3445886.html
Copyright © 2011-2022 走看看