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].
    *
    * “删除重复项”的后续操作:
    * 如果最多允许重复两次呢?
    * 例如,
    * 给定排序数组a=[1,1,1,2,2,3],
    * 函数返回的长度应为5,现在a为[1,1,2,2,3]。
    */

    因为本题是 允许重复两次的数,所以我们将count = 2,来进行循环。
    /**
     * 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].
     *
     * “删除重复项”的后续操作:
     * 如果最多允许重复两次呢?
     * 例如,
     * 给定排序数组a=[1,1,1,2,2,3],
     * 函数返回的长度应为5,现在a为[1,1,2,2,3]。
     */
    
    public class Main48 {
        public static void main(String[] args) {
            int[] A = {1,1,1,2};
            System.out.println(Main48.removeDuplicates(A));
        }
    
        public static int removeDuplicates(int[] A) {
            if (A == null) {
                return 0;
            }
            if (A.length<=2) {
                return A.length;
            }
            int count = 2;
            for (int i=2;i<A.length;i++) {//如果一样的话 就跳过。
           if (A[i] != A[count-2]) { //一旦跟它前面的第二个数不一样 就相当于加入数组中,覆盖前面循环一样的数的位置。
                           A[count++] = A[i]; } } return count; } }

      

  • 相关阅读:
    matlab做聚类分析
    《帝王三部曲》——二月河
    Sublime Text3--安装使用教程资料整理
    CentOS7没有ftp命令的解决方法
    CentOS7没有telnet命令的解决方法
    程序员如何学习英语
    程序员指法训练
    C/C++语言的学习策略
    零基础、非计算机相关专业的如何转型程序员
    IT培训机构那些不得不说的事儿
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11344641.html
Copyright © 2011-2022 走看看