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是用来在消除重复赋值前保存原数组的值的。




原文地址:https://www.cnblogs.com/dosmile/p/6444477.html