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

    先排序,然后有三种允许的情况可以添加。

     1 public class Solution {
     2     public int removeDuplicates(int[] A) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         Arrays.sort(A);
     6         int Len = 0;
     7         for (int i = 0; i < A.length; i++)
     8             if (i == 0 || A[i - 1] != A[i] || ( i != 0 && A[i] == A[i - 1] && (Len < 2 || A[Len - 1] != A[Len - 2])) )
     9                 A[Len ++] = A[i];
    10         return Len;
    11     }
    12 }

     第三遍:

     1 public class Solution {
     2     public int removeDuplicates(int[] A) {
     3         if(A.length < 3) return A.length;
     4         int cur = 2;
     5         for(int i = 2; i < A.length; i ++){
     6             if(A[i] != A[cur - 2]) A[cur ++] = A[i];
     7         }
     8         return cur;
     9     }
    10 }
  • 相关阅读:
    一个网站架构的变迁
    网络编程
    http协议篇
    第1篇 编程能力是什么
    django中的cookies和session机制
    django的认证与授权系统
    python的异常处理
    第0篇
    mysql优化和全局管理杂记
    k8s中pod的资源配置详解
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3420611.html
Copyright © 2011-2022 走看看