File tree Expand file tree Collapse file tree 1 file changed +6
-19
lines changed Expand file tree Collapse file tree 1 file changed +6
-19
lines changed Original file line number Diff line number Diff line change 1
1
#include < bits/stdc++.h>
2
2
using namespace std ;
3
3
4
- int removeDuplicates (vector<int > &arr, int n)
5
- {
6
- // remember the array is sorted
7
- int i = 0 ;
8
- for (int j = 1 ; j < n; j++)
9
- {
10
- // if we find an element not equal to previous unique element, we do the in-place change
11
- // of the newly found element one place after the previously found unique element
12
- // and now the newly found unique element becomes the previously found unique element
13
- // for further searching of another unique element if there exists one
14
- if (arr[i] != arr[j])
15
- {
16
- arr[i + 1 ] = arr[j];
17
- i++;
18
- }
4
+ int removeDuplicates (vector<int >& a) {
5
+ int i = 1 , j = 0 , n = a.size ();
6
+ while (i < n) {
7
+ if (a[i] == a[j]) i++;
8
+ else swap (a[++j], a[i++]);
19
9
}
20
- // In the end, the i pointer would be standing at a position where the last unique element
21
- // stands, and since the index starts with 0 and we want the no. of unique elements in the
22
- // array, we return (i+1)
23
- return (i + 1 );
10
+ return j + 1 ;
24
11
}
25
12
26
13
int main ()
You can’t perform that action at this time.
0 commit comments