使用 C++ 打印给定整数数组的所有不同元素
在这个问题中,我们给定一个整数数组。我们的任务是打印数组中的所有不同元素。输出应该只包含不同的值。
让我们举个例子来理解这个问题
Input: array = {1, 5, 7, 12, 1, 6, 10, 7, 5}
Output: 1 5 7 12 6 10为了解决这个问题,我们将不得不检查数组元素的唯一性。为此,我们将使用两个嵌套循环,外部循环将取值,内部循环将用它检查其余的值。如果存在多个值,则只打印一个。
示例
此代码展示了我们解决方案的实现,
#include <iostream>
using namespace std;
void printDistinctValues(int arr[], int n) {
for (int i=0; i<n; i++){
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
cout<<arr[i]<<"\t";
}
}
int main(){
int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Distinct values of the array are :\n";
printDistinctValues(arr, n);
return 0;
}输出
Distinct elements of the array are − 1 5 6 7 10 12
此解决方案简单易懂,但使用了两个循环,这使得其复杂度为 n2 阶。
另一种更复杂的方法是使用排序。在排序后的数组中,相似数字的出现会变得连续。现在,我们可以轻松地打印不同的元素,并且它占用的空间更少。
示例
我们逻辑的实现 -
#include <bits/stdc++.h>
using namespace std;
void printDistinctElements(int arr[], int n){
sort(arr, arr + n);
for (int i=0; i<n; i++){
while (i < n-1 && arr[i] == arr[i+1])
i++;
cout<<arr[i]<<"\t";
}
}
int main(){
int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Distinct elements of the array are :\n";
printDistinctElements(arr, n);
return 0;
}输出
Distinct elements of the array are − 1 5 6 7 10 12
另一种更有效的解决方案是跟踪数组中已访问的元素。我们将遍历数组并跟踪数组中所有已访问的元素。
示例
此代码展示了我们解决方案的实现,
#include<bits/stdc++.h>
using namespace std;
void printDistinctElements(int arr[],int n) {
unordered_set<int> visited;
for (int i=0; i<n; i++){
if (visited.find(arr[i])==visited.end()){
visited.insert(arr[i]);
cout<<arr[i]<<"\t";
}
}
}
int main () {
int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
int n=7;
cout<<"Distinct numbers of the array are :\n";
printDistinctElements(arr,n);
return 0;
}输出
Distinct numbers of the array are − 1 5 7 12 6 10
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP