您的位置:首页 > 其它

LeetCode | Remove Duplicates from Sorted Array II

2014-11-03 17:31 399 查看
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是用来在消除重复赋值前保存原数组的值的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 去重复 数组