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; } }

      

  • 相关阅读:
    Beta 冲刺(1/7)
    福大软工 · 第十次作业
    福大软工 · BETA 版冲刺前准备(团队)
    福大软工 · 第十一次作业
    Alpha 冲刺 (10/10)
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    vue 写一个瀑布流插件
    微信小程序页面滚动到指定位置
    写一个vue的滚动条插件
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11344641.html
Copyright © 2011-2022 走看看