计算C ++中数组中的不同元素
我们得到了一个任意大小的未排序数组,其中包含重复元素,并且任务是计算数组中不同元素的数量。
数组是一种数据结构,可以存储相同类型的元素的固定大小的顺序集合。数组用于存储数据集合,但是将数组视为相同类型的变量集合通常会更有用。
例如
Input− int arr[] = {1, 1, 2, 3, 3, 4, 4}Output − count is 4解释-在给定的数组中,有4个不同的元素,分别是1、2、3、4,但是数组的大小为7,因为它包含重复的元素,我们的任务是删除重复项,然后对数组元素进行计数。
Input − int arr[] = {1, 2, 3, 4, 5, 5, 5, 5}Output − count is 5Explanation−Inthegivenarraythereare5distinctelementsandthoseare1,2,3,4and5butthesizeofarrayis8asitcontainsrepetitiveelementsandourtaskwastoremovetheduplicatesandthencountthearrayelements.
Approachusedinthebelowprogramisasfollows
Usingsortfunction()
Createanarrayoflet’ssay,arr[]
Calculatethelengthofanarrayusingthelength()functionthatwillreturnan
integervalueaspertheelementsinanarray.
Callthesortfunctionandpassthearrayandthesizeofanarrayasaparameter.
Takeatemporaryvariablethatwillstorethecountofdistinctelements.
Startaloopforwithito0tilliislessthanthesizeofanarray
Insidetheloop,runwhilei<size-1andarr[i]=arr[i+1]
Insidethewhile,incrementthevalueofi
在里面,增加count的值
返回计数
打印结果。
没有排序
创建一个数组,比如说arr[]
使用length()函数将根据数组中的元素返回整数值来计算数组的长度。
取一个临时变量,它将存储不同元素的计数。
从i到1开始循环,直到i小于数组的大小
在循环内,将j设置为0并开始另一个循环,其中j为0且j小于i并递增jwth1
在此循环中,检查arr[i]=arr[j]然后中断
在此循环中,检查i=j,然后将计数加1
返回计数
打印结果
示例
带排序
#include <algorithm>
#include <iostream>
using namespace std;
int distinct_elements(int arr[], int n){
//排序数组
sort(arr, arr + n);
//遍历排序的数组
int count = 0;
for (int i = 0; i < n; i++){
//找到重复项时移动索引
while (i < n - 1 && arr[i] == arr[i + 1]){
i++;
}
count++;
}
return count;
}
//主要功能
int main(){
int arr[] = { 3, 6, 5, 8, 2, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout <<"count is "<<distinct_elements(arr, n);
return 0;
}输出结果
如果运行上面的代码,我们将获得以下输出-
count is 6
示例
不排序
#include <iostream>
using namespace std;
int countDistinct(int a[], int size){
int i, j, count = 1;
for (i = 1; i < size; i++){
for (j = 0; j < i; j++){
if (a[i] == a[j]){
break;
}
}
if (i == j){
count++;
}
}
return count;
}
//主要功能
int main(){
int a[] = { 3, 6, 5, 8, 2, 3, 4 };
int size = sizeof(a) / sizeof(a[0]);
cout << "count is "<<countDistinct(a, size);
return 0;
}输出结果
如果运行上面的代码,我们将获得以下输出-
count is 6