Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 13a22bf

Browse files
made it short and sweet
1 parent 7c692a8 commit 13a22bf

File tree

1 file changed

+6
-19
lines changed

1 file changed

+6
-19
lines changed

‎CS_20_RemoveDuplicatesFromSortedArray.cpp‎

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,13 @@
11
#include <bits/stdc++.h>
22
using namespace std;
33

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++]);
199
}
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;
2411
}
2512

2613
int main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /