Skip to content

Commit 78b5485

Browse files
authored
Merge pull request div-bargali#802 from Anish0203/add-code4
Remove Duplicates from sorted array
2 parents 01834a8 + 0b1af9f commit 78b5485

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
2+
3+
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
4+
*/
5+
#include<bits/stdc++.h>
6+
using namespace std;
7+
int removeDuplicates(vector<int>& nums) // this function returns length
8+
{
9+
int l = 0, i, c = 0;
10+
11+
for (i = 0; i < nums.size(); i++) // l stores the number of distcinct elements in the array
12+
{
13+
if (i == 0)
14+
{
15+
l++; continue;
16+
}
17+
if (nums[i] == nums[i - 1])
18+
continue;
19+
else
20+
l++;
21+
}
22+
for (i = 0; i < nums.size(); i++)
23+
{
24+
if (i == 0)
25+
{
26+
c++; continue;
27+
}
28+
if (nums[i] != nums[i - 1]) //as soon a new element is encountered it is paced at index c
29+
{
30+
nums[c] = nums[i];
31+
c++;
32+
if (c == l) //it checks all the distcinct elements have been alloted in the first l indices
33+
break;
34+
}
35+
}
36+
return l;
37+
}
38+
int main()
39+
{
40+
vector<int> nums;
41+
int n, i;
42+
cin >> n;
43+
for (i = 0; i < n; i++) //takes input from user
44+
{
45+
int b;
46+
cin >> b;
47+
nums.push_back(b);
48+
}
49+
int len = removeDuplicates(nums);
50+
for (i = 0; i < len; i++) //prints the required distinct elements
51+
cout << nums[i] << " ";
52+
return 0;
53+
}

0 commit comments

Comments
 (0)