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

     

    //思想类似于前天的去数组重复,用length标记满足重复最多允许两次的数组的长度
    public class Solution {
        public int removeDuplicates(int[] A) {
            if (A.length <= 2) return A.length;
            
             int length = 2;  
             int prepre = A[0];  
             int pre = A[1];  
             
             for (int i=2; i<A.length; i++){          // for (int i=2; i<A.length; i++){
                 if (A[i] != prepre){                 //     if (A[i] != A[i-2]){
                     A[length++] = A[i];              //         A[length++] = A[i];
                 }                                    //      }
                 prepre = pre;                        // }
                 pre = A[i];                          
             }                                        // return length;
             return length; 
        }
    }

    注解:注意右边的程序是有错误的。

    由于题目允许在数组中重复两次,且数组是sorted的,故每次for循环取A[i]与它前面的前面相比较,如果两者相等,则中间的肯定也相等,即为一个不符合要求的三重复。但注意:不能写成右边的 A[i]!=A[i-2]形式。

    举例:数组1 1 1 2 2 3

    在i=3的循环后,数组变为 1 1 2 2 2 3,length=3,A[2]=2,而prepre是前一次i=3循环时由pre赋给的,prepre=原A[2]=1,这点很重要。

    在i=4的循环时,判断A[4]!=prepre,而不是判断A[4]!=A[2],否则只有一个三重复的数组由于判断A[2]=A[4]而又导入了一个额外的三重复。

    prepre与pre是用来在消除重复赋值前保存原数组的值的。




  • 相关阅读:
    C#读取系统信息
    C# 读取驱动器盘符及信息
    for循环里的break,continue和return有什么差别
    monkey
    ZXing
    python中os模块的常用接口和异常中Exception的运用
    python中的字典应用实例
    python中的列表和字典
    python中如何单独测试一个函数的作用
    数据挖掘概念与技术PDF
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444477.html
Copyright © 2011-2022 走看看