标题: |
Remove Duplicates from Sorted Array II |
通过率: | 30.7% |
难度: | 中等 |
ollow 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]
.
做过第一个版本。就是去除重复的,用一个指针记录真实应该到哪个位置就行,
现在时做去除大于2的重复,依然与1一样,有个区别就是用一个标志位来判断是不是大于2就行
具体看代码:
1 public class Solution { 2 public int removeDuplicates(int[] A) { 3 if(A.length==0) return 0; 4 int index=1; 5 int flag=0; 6 for(int i=1;i<A.length;i++){ 7 if(A[i]!=A[i-1]){ 8 A[index]=A[i]; 9 index++; 10 flag=0; 11 } 12 else if(A[i]==A[i-1]){ 13 if(flag!=2){ 14 A[index]=A[i]; 15 index++; 16 flag=2; 17 } 18 } 19 } 20 return index; 21 } 22 }