Skip to content

Commit 90add6c

Browse files
committed
Problem 165: Remove duplicates from array
1 parent 707f86a commit 90add6c

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -235,5 +235,6 @@ Include contains single header implementation of data structures and some algori
235235
| Write a function that takes a string as input and reverse only the vowels of a string.|[reverse_vowels.cpp](leet_code_problems/reverse_vowels.cpp)|
236236
| Given a string, sort it in decreasing order based on the frequency of characters.For example: <ul><li>Input: cccbbbbaa Output: bbbcccaa</li></ul>| [sortCharByFrequency.cpp](leet_code_problems/sortCharByFrequency.cpp)|
237237
|Product of Array Except Self. Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].| [product_except_self.cpp](leet_code_problems/product_except_self.cpp)|
238+
|Given a sorted array, remove duplicates in place and return the new length. It doesn't matter what is in array beyond the unique elements size. Expected O(1) space and O(n) time complexity.| [remove_duplicates.cpp](leet_code_problems/remove_duplicates.cpp) |
238239

239240

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Given a sorted array, remove duplicates in place and return the new length.
3+
* It doesn't matter what is in array beyond the unique elements size.
4+
* Expected O(1) space and O(n) time complexity.
5+
* Input : {1, 1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7}
6+
* Output: {1, 2, 3, 4, 5, 6, 7}
7+
*/
8+
9+
#include <iostream>
10+
#include <vector>
11+
12+
13+
template <typename T>
14+
void swap(T& a, T& b)
15+
{
16+
T c(std::move(a));
17+
a = std::move(b);
18+
b = std::move(c);
19+
}
20+
21+
unsigned int remove_duplicates(std::vector<int>& nums)
22+
{
23+
unsigned int i = 0;
24+
for (unsigned int j = 0; j < nums.size(); ++j) {
25+
if (nums[i] != nums[j]) {
26+
swap(nums[++i], nums[j]);
27+
}
28+
}
29+
return i+1;
30+
}
31+
32+
void print_vector(const std::vector<int>& vec, unsigned int n)
33+
{
34+
for (unsigned int i = 0; i < n; ++i) {
35+
std::cout << vec[i] << " ";
36+
}
37+
std::cout << std::endl;
38+
}
39+
40+
int main()
41+
{
42+
std::vector<int> vec{1, 1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7};
43+
std::cout << "Original vector:";
44+
print_vector(vec, vec.size());
45+
unsigned int size = remove_duplicates(vec);
46+
std::cout << "Output vector:";
47+
print_vector(vec, size);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)