File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
C++/Data-Structures/Array Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments