package com.ytx.array;
/** 题目: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].
*
* @author yuantian xin
*
* 在数组中最多允许一个元素重复出现两次,如果给你一个有序数组,请设计算法处理满足要求,然后返回数组新的长度。
*
* 思路:这是第二版本,但还是第一版的双指针思想,一个快指针i,和一个慢指针index,这次再加一个重复标志量dup即可,
* 如果题目改成允许一个元素重复出现三次,四次或者n次,我们只需要改变dup即可。
*
*
*
*/
public class Remove_duplicates_from_sorted_array_ii {
public int removeDuplicates(int[] A) {
int len = A.length;
if (len == 0 || A == null ) return 0;
int index = 1;
int dup = 1;//重复次数的标志量
for (int i = 1; i < len; ++i) {
if (A[i] == A[i - 1]) {
dup++;//如果两个元素相等,dup加一
if(dup > 2) continue;//根据题意,只有当重复次数大于2的时候,才让快指针大于慢指针。
A[index ++] = A[i];
} else {
A[index ++] = A[i];
dup = 1;//把标志量回置为1,不然一直增大毫无意义
}
}
return index;
}
public static void main(String[] args) {
int[] A = {3,3,3,4,4,4,6,9,9,9,9,10};
/*int A[] = {1};*/
int newLength = new Remove_duplicates_from_sorted_array_ii().removeDuplicates(A);
System.out.println(newLength);
for(int i = 0; i < newLength; i++) {
System.out.print(A[i] + " ");
}
}
}