地址:http://oj.leetcode.com/problems/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]
.
参考代码:
class Solution {
public:
int removeDuplicates(int A[], int n) {
map<int, int>dm;
for(int i = 0; i < n; ++i)
{
if(dm[A[i]]==0)
{
dm[A[i]] = 1;
}
else if(dm[A[i]]==1)
{
dm[A[i]] = 2;
}
else
{
for(int j = i; j < n-1; ++j)
{
A[j] = A[j+1];
}
--i;
--n;
}
}
return n;
}
};
//SECOND TRIAL, in placeclass Solution {public :int removeDuplicates ( int A [], int n ) {if ( n <= 2 )return n ;int len = 1 ;bool flag = true ;for ( int i = 1 ; i < n ; ++ i ){if ( A [ i ] != A [ len - 1 ]){A [ len ++ ] = A [ i ];flag = true ;}else if ( flag ){A [ len ++ ] = A [ i ];flag = false ;}}return len ;}};
python:
class Solution :# @param A a list of integers# @return an integerdef removeDuplicates ( self , A ):if len ( A ) <= 2 :return len ( A )cnt = 1flag = Truefor i in range ( 1 , len ( A )):if A [ i ] != A [ i - 1 ]:flag = TrueA [ cnt ] = A [ i ]cnt += 1elif flag :flag = FalseA [ cnt ] = A [ i ]cnt += 1return cnt