使用 Set 数据结构从未排序的数组中删除重复项
给定一个未排序的整数数组,在删除重复元素后打印该数组。我们需要根据它们的第一次出现来打印不同的数组元素。
例子:
Input: arr[] = { 1, 2, 5, 1, 7, 2, 4, 2}
Output: 1 2 5 7 4
Explanation: {1, 2} appear more than one time.
Input: arr[] = { 3, 3, 4, 1, 1}
Output: 3 4 1
方法:
- 拿一套
- 在 Set 中插入所有数组元素。 Set 不允许重复,并且像 LinkedHashSet 这样的集合保持插入顺序,因此它将删除重复项,并且元素将以插入时的相同顺序打印。
- 将形成的集合转换为数组。
- 打印 Set 的元素。
下面是上述方法的实现:
C++
// CPP program to remove duplicates
// from unsorted array
#include
using namespace std;
// Function to remove duplicate from array
void removeDuplicates(int arr[], int n)
{
unordered_set s;
// adding elements to LinkedHashSet
for (int i = 0; i < n; i++)
s.insert(arr[i]);
// Print the elements of LinkedHashSet
cout << "[ ";
for (auto x : s)
cout << x << " ";
cout << "]";
}
// Driver code
int main()
{
int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
removeDuplicates(arr, n);
}
// This code is contributed
// by Surendra_Gangwar
Java
// Java program to remove duplicates
// from unsorted array
import java.util.*;
class GFG {
// Function to remove duplicate from array
public static void removeDuplicates(int[] arr)
{
LinkedHashSet set
= new LinkedHashSet();
// adding elements to LinkedHashSet
for (int i = 0; i < arr.length; i++)
set.add(arr[i]);
// Print the elements of LinkedHashSet
System.out.print(set);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };
// Function call
removeDuplicates(arr);
}
}
Python3
# Python3 program to remove duplicates
def removeDulipcates(arr):
# convert the arr into set and then into list
return list(set(arr))
# Driver Code
arr = [1, 2, 5, 1, 7, 2, 4, 2]
# Function call
print(removeDulipcates(arr))
# This code is contributed
# by Mohit Kumar
C#
// C# program to remove duplicates
// from unsorted array
using System;
using System.Collections.Generic;
class GFG
{
// Function to remove duplicate from array
public static void removeDuplicates(int[] arr)
{
HashSet set = new HashSet();
// adding elements to LinkedHashSet
for (int i = 0; i < arr.Length; i++)
set.Add(arr[i]);
// Print the elements of HashSet
foreach(int item in set) Console.Write(item + ", ");
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 1, 2, 5, 1, 7, 2, 4, 2 };
// Function call
removeDuplicates(arr);
}
}
// This code is contributed by 29AjayKumar
Javascript
输出
[ 4 7 5 1 2 ]
时间复杂度:O(N)