从小素数数组中删除重复项
给定一个素数数组,使得素数的范围很小。从数组中删除重复项。
例子:
Input: arr[] = {3, 5, 7, 2, 2, 5, 7, 7};
Output: arr[] = {2, 3, 5, 7}
All the duplicates are removed from
the array. The output can be printed in any order.
Input: arr[] = {3, 5, 7, 3, 3, 13, 5, 13, 29, 13};
Output: arr[] = {3, 5, 7, 13, 29}
All the duplicates are removed from
the array. The output can be printed in any order.
来源:亚马逊面试题
方法 1 :该方法讨论了采用 O(n 2 ) 时间复杂度的简单方法。
方法:所以基本思想是检查每个元素,无论它以前是否发生过。因此,该方法涉及保留两个循环,一个选择当前元素或索引,内部循环检查该元素是否先前出现过。
算法:
- 首先运行两个循环。
- 一个一个地选择所有元素。
- 对于每个选择的元素,检查它是否已经发生。
- 如果已经看到,则忽略它,否则将其添加到数组中。
C++
// A C++ program to implement Naive
// approach to remove duplicates.
#include
using namespace std;
int removeDups(vector& vect)
{
int res_ind = 1;
// Loop invariant: Elements from vect[0]
// to vect[res_ind-1] are unique.
for (int i = 1; i < vect.size(); i++) {
int j;
for (j = 0; j < i; j++)
if (vect[i] == vect[j])
break;
if (j == i)
vect[res_ind++] = vect[i];
}
// Removes elements from vect[res_ind] to
// vect[end]
vect.erase(vect.begin() + res_ind, vect.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Java program to implement Naive
// approach to remove duplicates
class GFG {
static int[] removeDups(int[] vect)
{
int res_ind = 1;
// Loop invariant: Elements from vect[0]
// to vect[res_ind-1] are unique.
for (int i = 1; i < vect.length; i++) {
int j;
for (j = 0; j < i; j++)
if (vect[i] == vect[j])
break;
if (j == i)
vect[res_ind++] = vect[i];
}
// Removes elements from vect[res_ind]
// to vect[end]
int[] new_arr = new int[res_ind];
for (int i = 0; i < res_ind; i++)
new_arr[i] = vect[i];
return new_arr;
}
// Driver Code
public static void main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.length; i++)
System.out.print(vect[i] + " ");
System.out.println();
}
}
// This code is contributed by
// sanjeev2552
Python3
# A Python3 program to implement
# Naive approach to remove duplicates.
def removeDups(vect):
res_ind = 1
# Loop invariant : Elements from vect[0]
# to vect[res_ind-1] are unique.
for i in range(1, len(vect)):
j = 0
while (j < i):
if (vect[i] == vect[j]):
break
j += 1
if (j == i):
vect[res_ind] = vect[i]
res_ind += 1
# Removes elements from
# vect[res_ind] to vect[end]
return vect[0:res_ind]
# Driver code
vect = [3, 5, 7, 2, 2, 5, 7, 7]
vect = removeDups(vect)
for i in range(len(vect)):
print(vect[i], end = " ")
# This code is contributed
# by mohit kumar
C#
// C# program to implement Naive approach
// to remove duplicates
using System;
class GFG {
static int[] removeDups(int[] vect)
{
int res_ind = 1;
// Loop invariant : Elements from vect[0]
// to vect[res_ind-1] are unique.
for (int i = 1; i < vect.Length; i++) {
int j;
for (j = 0; j < i; j++)
if (vect[i] == vect[j])
break;
if (j == i)
vect[res_ind++] = vect[i];
}
// Removes elements from vect[res_ind]
// to vect[end]
int[] new_arr = new int[res_ind];
for (int i = 0; i < res_ind; i++)
new_arr[i] = vect[i];
return new_arr;
}
// Driver Code
public static void Main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.Length; i++)
Console.Write(vect[i] + " ");
Console.WriteLine();
}
}
// This code is contributed by Rajput-Ji
Javascript
C++
// C++ program to remove duplicates using Sorting
#include
using namespace std;
int removeDups(vector& vect)
{
// Sort the vector
sort(vect.begin(), vect.end());
// unique() removes adjacent duplicates.
// unique function puts all unique elements at
// the beginning and returns iterator pointing
// to the first element after unique element.
// Erase function removes elements between two
// given iterators
vect.erase(unique(vect.begin(), vect.end()),
vect.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Java program to remove duplicates using Sorting
import java.util.*;
class GFG {
static int[] removeDups(int[] vect)
{
// sort the array
Arrays.sort(vect);
// pointer
int first = 1;
// remove duplicate elements
for (int i = 1; i < vect.length; i++)
if (vect[i] != vect[i - 1])
vect[first++] = vect[i];
// mark rest of elements to INT_MAX
for (int i = first; i < vect.length; i++)
vect[i] = Integer.MAX_VALUE;
return vect;
}
// Driver code
public static void main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.length; i++) {
if (vect[i] == Integer.MAX_VALUE)
break;
System.out.print(vect[i] + " ");
}
}
}
Python3
# Python3 program to remove duplicates
# using Sorting
import sys
def removeDups(vect):
# Sort the array
vect.sort()
# Pointer
first = 1
# Remove duplicate elements
for i in range(1, len(vect)):
if (vect[i] != vect[i - 1]):
vect[first] = vect[i]
first += 1
# Mark rest of elements to INT_MAX
for i in range(first, len(vect)):
vect[i] = sys.maxsize
return vect
# Driver code
vect = [ 3, 5, 7, 2, 2, 5, 7, 7 ]
vect = removeDups(vect)
for i in range(len(vect)):
if (vect[i] == sys.maxsize):
break
print(vect[i], end = " ")
# This code is contributed by avanitrachhadiya2155
C#
// C# program to remove duplicates using Sorting
using System;
class GFG
{
static int[] removeDups(int[] vect)
{
// sort the array
Array.Sort(vect);
// pointer
int first = 1;
// remove duplicate elements
for (int i = 1; i < vect.Length; i++)
if (vect[i] != vect[i - 1])
vect[first++] = vect[i];
// mark rest of elements to INT_MAX
for (int i = first; i < vect.Length; i++)
vect[i] = int.MaxValue;
return vect;
}
// Driver code
public static void Main(params string[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.Length; i++)
{
if (vect[i] == int.MaxValue)
break;
Console.Write(vect[i] + " ");
}
}
}
// This code is contributed by rutvik_56.
Javascript
C++
// C++ program to remove duplicates using Hashing
#include
using namespace std;
int removeDups(vector& vect)
{
// Create a set from vector elements
unordered_set s(vect.begin(), vect.end());
// Take elements from set and put back in
// vect[]
vect.assign(s.begin(), s.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Java program to implement Naive approach to
// remove duplicates.
import java.util.*;
class GFG {
static void removeDups(Vector vect)
{
// Create a set from vector elements
Set set = new HashSet(vect);
// Take elements from set and put back in
// vect[]
vect.clear();
vect.addAll(set);
}
// Driver code
public static void main(String[] args)
{
Integer arr[] = { 3, 5, 7, 2, 2, 5, 7, 7 };
Vector vect
= new Vector(
Arrays.asList(arr));
removeDups(vect);
for (int i = 0; i < vect.size(); i++) {
System.out.print(vect.get(i) + " ");
}
}
}
/* This code contributed by PrinciRaj1992 */
Python3
# Python3 program to remove duplicates using Hashing
def removeDups():
global vect
# Create a set from vector elements
s = set(vect)
# Take elements from set and put back in
# vect[]
vect = s
# Driver code
vect = [3, 5, 7, 2, 2, 5, 7, 7]
removeDups()
for i in vect:
print(i, end = " ")
# This code is contributed by shubhamsingh10
C#
// C# program to implement Naive approach to
// remove duplicates.
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static List removeDups(List vect)
{
// Create a set from vector elements
HashSet set = new HashSet(vect);
// Take elements from set and put back in
// vect[]
vect.Clear();
vect = set.ToList();
return vect;
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 3, 5, 7, 2, 2, 5, 7, 7 };
List vect = new List(arr);
vect = removeDups(vect);
for (int i = 0; i < vect.Count; i++) {
Console.Write(vect[i] + " ");
}
}
}
// This code is contributed by PrinciRaj1992
Javascript
C++
// Removes duplicates using multiplication of
// distinct primes in array
#include
using namespace std;
int removeDups(vector& vect)
{
long long int prod = vect[0];
int res_ind = 1;
for (int i = 1; i < vect.size(); i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
vect.erase(vect.begin() + res_ind, vect.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Removes duplicates using multiplication of
// distinct primes in array
import java.util.*;
class GFG {
static int[] removeDups(int[] vect)
{
int prod = vect[0];
int res_ind = 1;
for (int i = 1; i < vect.length; i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
return Arrays.copyOf(vect, res_ind);
}
// Driver code
public static void main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.length; i++)
System.out.print(vect[i] + " ");
}
}
// This code is contributed by 29AjayKumar
Python3
# Removes duplicates using multiplication of
# distinct primes in array
def removeDups(vect):
prod = vect[0]
res_ind = 1
i = 1
while (i < len(vect)):
if (prod % vect[i] != 0):
vect[res_ind] = vect[i]
res_ind += 1
prod *= vect[i]
vect = vect[:res_ind + 2]
i += 1
return vect
# Driver code
vect = [3, 5, 7, 2, 2, 5, 7, 7]
vect = removeDups(vect)
for i in range(len(vect)):
print(vect[i], end =" ")
# This code is contributed by SHUBHAMSINGH10
C#
// Removes duplicates using multiplication of
// distinct primes in array
using System;
class GFG {
static int[] removeDups(int[] vect)
{
int prod = vect[0];
int res_ind = 1;
for (int i = 1; i < vect.Length; i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
int[] temp = new int[vect.Length - res_ind];
Array.Copy(vect, 0, temp, 0, temp.Length);
return temp;
}
// Driver code
public static void Main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.Length; i++)
Console.Write(vect[i] + " ");
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
3 5 7 2
复杂性分析:
- 时间复杂度: O(n 2 )。
由于使用了两个嵌套循环,因此时间复杂度变为 O(n 2 )。 - 空间复杂度: O(n)。
由于使用了一个额外的数组来存储元素,因此空间复杂度为 O(n)。
方法 2 :该方法涉及排序技术,需要 O(n log n) 时间。
方法:与以前的方法相比,更好的解决方案是先对数组进行排序,然后从排序后的数组中删除所有相似的相邻元素。
算法:
- 首先对数组进行排序。
- 可以巧妙地避免对额外空间的需求。保留两个变量, first = 1 和i = 1。
- 遍历数组从第二个元素到末尾。
- 对于每个元素,如果该元素不等于前一个元素,则array[first++] = array[i] ,其中i是循环的计数器。
- 所以没有重复的数组的长度是第一个,删除其余元素。
注意:在 CPP 中有一些内置函数,如sort()用于排序和unique()用于删除相邻的重复项。 unique()函数将所有唯一元素放在开头,并返回一个迭代器,该迭代器指向唯一元素之后的第一个元素。 erase()函数删除两个给定迭代器之间的元素。
C++
// C++ program to remove duplicates using Sorting
#include
using namespace std;
int removeDups(vector& vect)
{
// Sort the vector
sort(vect.begin(), vect.end());
// unique() removes adjacent duplicates.
// unique function puts all unique elements at
// the beginning and returns iterator pointing
// to the first element after unique element.
// Erase function removes elements between two
// given iterators
vect.erase(unique(vect.begin(), vect.end()),
vect.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Java program to remove duplicates using Sorting
import java.util.*;
class GFG {
static int[] removeDups(int[] vect)
{
// sort the array
Arrays.sort(vect);
// pointer
int first = 1;
// remove duplicate elements
for (int i = 1; i < vect.length; i++)
if (vect[i] != vect[i - 1])
vect[first++] = vect[i];
// mark rest of elements to INT_MAX
for (int i = first; i < vect.length; i++)
vect[i] = Integer.MAX_VALUE;
return vect;
}
// Driver code
public static void main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.length; i++) {
if (vect[i] == Integer.MAX_VALUE)
break;
System.out.print(vect[i] + " ");
}
}
}
Python3
# Python3 program to remove duplicates
# using Sorting
import sys
def removeDups(vect):
# Sort the array
vect.sort()
# Pointer
first = 1
# Remove duplicate elements
for i in range(1, len(vect)):
if (vect[i] != vect[i - 1]):
vect[first] = vect[i]
first += 1
# Mark rest of elements to INT_MAX
for i in range(first, len(vect)):
vect[i] = sys.maxsize
return vect
# Driver code
vect = [ 3, 5, 7, 2, 2, 5, 7, 7 ]
vect = removeDups(vect)
for i in range(len(vect)):
if (vect[i] == sys.maxsize):
break
print(vect[i], end = " ")
# This code is contributed by avanitrachhadiya2155
C#
// C# program to remove duplicates using Sorting
using System;
class GFG
{
static int[] removeDups(int[] vect)
{
// sort the array
Array.Sort(vect);
// pointer
int first = 1;
// remove duplicate elements
for (int i = 1; i < vect.Length; i++)
if (vect[i] != vect[i - 1])
vect[first++] = vect[i];
// mark rest of elements to INT_MAX
for (int i = first; i < vect.Length; i++)
vect[i] = int.MaxValue;
return vect;
}
// Driver code
public static void Main(params string[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.Length; i++)
{
if (vect[i] == int.MaxValue)
break;
Console.Write(vect[i] + " ");
}
}
}
// This code is contributed by rutvik_56.
Javascript
输出:
2 3 5 7
复杂性分析:
- 时间复杂度: O(n Log n)。
对数组进行排序需要O(n log n)时间复杂度,而移除相邻元素需要O(n)时间复杂度。 - 辅助空间: O(1)
由于不需要额外的空间,空间复杂度是恒定的。
方法3 :该方法涉及Hashing技术,耗时O(n)。
方法:这种方法的时间复杂度可以降低,但空间复杂度会有所损失。这涉及使用哈希,其中数字在 HashMap 中标记,因此如果再次遇到该数字,则将其从数组中删除。
算法:
- 使用哈希集。 HashSet 只存储唯一元素。
- 众所周知,如果将两个相同的元素放入一个 HashSet 中,则 HashSet 只存储一个元素(所有重复的元素都消失了)
- 从头到尾遍历数组。
- 对于每个元素,将元素插入 HashSet
- 现在遍历HashSet,将HashSet中的元素放入数组中
C++
// C++ program to remove duplicates using Hashing
#include
using namespace std;
int removeDups(vector& vect)
{
// Create a set from vector elements
unordered_set s(vect.begin(), vect.end());
// Take elements from set and put back in
// vect[]
vect.assign(s.begin(), s.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Java program to implement Naive approach to
// remove duplicates.
import java.util.*;
class GFG {
static void removeDups(Vector vect)
{
// Create a set from vector elements
Set set = new HashSet(vect);
// Take elements from set and put back in
// vect[]
vect.clear();
vect.addAll(set);
}
// Driver code
public static void main(String[] args)
{
Integer arr[] = { 3, 5, 7, 2, 2, 5, 7, 7 };
Vector vect
= new Vector(
Arrays.asList(arr));
removeDups(vect);
for (int i = 0; i < vect.size(); i++) {
System.out.print(vect.get(i) + " ");
}
}
}
/* This code contributed by PrinciRaj1992 */
Python3
# Python3 program to remove duplicates using Hashing
def removeDups():
global vect
# Create a set from vector elements
s = set(vect)
# Take elements from set and put back in
# vect[]
vect = s
# Driver code
vect = [3, 5, 7, 2, 2, 5, 7, 7]
removeDups()
for i in vect:
print(i, end = " ")
# This code is contributed by shubhamsingh10
C#
// C# program to implement Naive approach to
// remove duplicates.
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static List removeDups(List vect)
{
// Create a set from vector elements
HashSet set = new HashSet(vect);
// Take elements from set and put back in
// vect[]
vect.Clear();
vect = set.ToList();
return vect;
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 3, 5, 7, 2, 2, 5, 7, 7 };
List vect = new List(arr);
vect = removeDups(vect);
for (int i = 0; i < vect.Count; i++) {
Console.Write(vect[i] + " ");
}
}
}
// This code is contributed by PrinciRaj1992
Javascript
输出:
2 7 5 3
复杂性分析:
- 时间复杂度: O(n)。
由于需要一次遍历来输入哈希图中的所有元素,因此时间复杂度为O(n) 。 - 辅助空间: O(n)。
为了在 HashSet 或 hashmap 中存储元素,需要O(n)空间复杂度。
方法 4 :这侧重于时间复杂度为 O(n) 的小范围值。
方法:这种方法仅适用于所有不同素数的乘积小于10^18并且数组中的所有数字都应该是素数的情况。除了 1 或该数字本身之外,没有除数的素数的性质用于得出解。当数组元素从数组中删除时,它们会保留一个值(乘积),该值将包含先前在数组中找到的所有不同素数的乘积,因此如果元素除以乘积,则可以肯定地证明该元素具有以前出现在数组中,因此该数字将被拒绝。
算法:
- 最初,保留一个变量 (p = 1)。
- 从头到尾遍历数组。
- 遍历时,检查 p 是否可以被第 i 个元素整除。如果为真,则删除该元素。
- 否则保留该元素并通过将该元素与乘积相乘来更新乘积 (p = p * arr[i])
C++
// Removes duplicates using multiplication of
// distinct primes in array
#include
using namespace std;
int removeDups(vector& vect)
{
long long int prod = vect[0];
int res_ind = 1;
for (int i = 1; i < vect.size(); i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
vect.erase(vect.begin() + res_ind, vect.end());
}
// Driver code
int main()
{
vector vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Java
// Removes duplicates using multiplication of
// distinct primes in array
import java.util.*;
class GFG {
static int[] removeDups(int[] vect)
{
int prod = vect[0];
int res_ind = 1;
for (int i = 1; i < vect.length; i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
return Arrays.copyOf(vect, res_ind);
}
// Driver code
public static void main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.length; i++)
System.out.print(vect[i] + " ");
}
}
// This code is contributed by 29AjayKumar
Python3
# Removes duplicates using multiplication of
# distinct primes in array
def removeDups(vect):
prod = vect[0]
res_ind = 1
i = 1
while (i < len(vect)):
if (prod % vect[i] != 0):
vect[res_ind] = vect[i]
res_ind += 1
prod *= vect[i]
vect = vect[:res_ind + 2]
i += 1
return vect
# Driver code
vect = [3, 5, 7, 2, 2, 5, 7, 7]
vect = removeDups(vect)
for i in range(len(vect)):
print(vect[i], end =" ")
# This code is contributed by SHUBHAMSINGH10
C#
// Removes duplicates using multiplication of
// distinct primes in array
using System;
class GFG {
static int[] removeDups(int[] vect)
{
int prod = vect[0];
int res_ind = 1;
for (int i = 1; i < vect.Length; i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
int[] temp = new int[vect.Length - res_ind];
Array.Copy(vect, 0, temp, 0, temp.Length);
return temp;
}
// Driver code
public static void Main(String[] args)
{
int[] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for (int i = 0; i < vect.Length; i++)
Console.Write(vect[i] + " ");
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
3 5 7 2
复杂性分析:
- 时间复杂度: O(n)。
要仅遍历数组一次,所需时间为O(n) 。 - 辅助空间: O(1)。
需要一个变量 p,因此空间复杂度是恒定的。
注意:如果数组中有任何组合,此解决方案将不起作用。