-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove-Duplicates-from-Sorted-Array.cpp
69 lines (51 loc) · 1.17 KB
/
Remove-Duplicates-from-Sorted-Array.cpp
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
/*
* Song Qiang <qiang.song@usc.edu> 2013
*
*/
/*
Given a sorted array, remove the duplicates in place such that each
element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in
place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
*/
#include <cmath>
#include <vector>
#include <numeric>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <sstream>
#include <limits>
#include <utility>
using namespace std;
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 0) return 0;
int i = 1;
int j = 1;
while (j < n)
{
if (A[j] == A[j - 1])
++j;
else
A[i++] = A[j++];
}
return i;
}
};
int
main(int argn, char** argv)
{
Solution s;
int A[] = {1, 1, 2};
int n = s.removeDuplicates(A, 3);
for (size_t i = 0; i < n; ++i)
cout << A[i] << "\t";
cout << endl;
}