-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove_Duplicates_from_Sorted_Array_II.cpp
More file actions
90 lines (74 loc) · 1.56 KB
/
Remove_Duplicates_from_Sorted_Array_II.cpp
File metadata and controls
90 lines (74 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
// Author : zheng yi xiong
// Date : 2015-01-08
/**********************************************************************************
*
* 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].
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (0 >= n)
{
return 0;
}
int pos = 0;
bool bCopy = true;
for (int i = 1; i < n; ++i)
{
if (A[pos] != A[i])
{
A[++pos] = A[i];
bCopy = true;
}
else if (bCopy)
{
bCopy = false;
A[++pos] = A[i];
}
}
return pos + 1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int maxN = 5;
int maxNumber = 3;
if ( argc > 2) {
maxN = _wtoi(argv[1]);
maxNumber = _wtoi(argv[2]);
}
int *pA = new int[maxN * maxNumber];
cout<<"sorted linked list:\n";
int n = 0;
srand(time(0));
for(int i = 1; i < maxN; ++i) {
int duplicate = rand() % maxNumber + 1;
for (int j = 0; j < duplicate; ++j)
{
pA[n++] = i;
cout<<" "<<pA[n - 1];
}
}
cout<<endl;
Solution so;
int iRet = so.removeDuplicates(pA, n);
cout<<"return array "<<iRet<<":\n ";
for(int i = 0; i < iRet; ++i)
{
cout<<" "<<pA[i];
}
cout<<endl;
delete []pA;
system("pause");
return 0;
}