How to Find the Unique Elements in an Array in C++?
Last Updated :
01 Mar, 2024
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the unique elements in an array in C++.
Example:
Input:
array = {1, 2, 1, 2, 2, 3, 4}
Output:
Unique elements in the array: 1 2 3 4
Find the Unique Elements in an Array in C++
To find the Unique elements in a std::array in C++, we can iterate through the array and store the array elements in a std::set because the set will store the unique elements of the array and ignore the duplicate values.
C++ Program to Find Unique Elements in an Array
The below program demonstrates how we can find the unique elements in an array in C++.
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
vector< int > arr = { 1, 2, 1, 2, 2, 3, 4 };
set< int > s;
s.insert(arr.begin(), arr.end());
cout << "Unique elements in the array: " ;
for ( auto it = s.begin(); it != s.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
Output
Unique elements in the array: 1 2 3 4
Time Complexity: O(N * log(N)), where N is the number of elements in the set.
Auxiliiary Space: O(N)
Share your thoughts in the comments
Please Login to comment...