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 5说明 − 在给定的数组中,有5个不同的元素,分别是1、2、3、4和5,但数组的大小为8,因为它包含重复元素,我们的任务是删除重复项,然后计算数组元素。
下面程序中使用的方案如下
使用sort()函数
创建一个数组,例如,arr[]
使用length()函数计算数组的长度,该函数将根据数组中的元素返回一个整数值。
调用sort函数,并将数组和数组的大小作为参数传递。
取一个临时变量,它将存储不同元素的个数。
启动一个for循环,从i为0开始,直到i小于数组的大小。
在循环内,运行while i < size-1 和 arr[i] = arr[i+1]
在while循环内,递增i的值
在for循环内,递增count的值
返回count
打印结果。
不排序
创建一个数组,例如,arr[]
使用length()函数计算数组的长度,该函数将根据数组中的元素返回一个整数值。
取一个临时变量,它将存储不同元素的个数。
启动一个for循环,从i为1开始,直到i小于数组的大小。
在循环内,设置j为0,并启动另一个for循环,从j为0开始,直到j小于i,并以1递增j。
在这个循环内,检查arr[i]是否等于arr[j],如果是,则中断。
在这个循环内,检查i是否等于j,如果是,则将count递增1。
返回count
打印结果。
示例
排序后
#include <algorithm>
#include <iostream>
using namespace std;
int distinct_elements(int arr[], int n){
// Sorting the array
sort(arr, arr + n);
// Traverse the sorted array
int count = 0;
for (int i = 0; i < n; i++){
// Moving the index when duplicate is found
while (i < n - 1 && arr[i] == arr[i + 1]){
i++;
}
count++;
}
return count;
}
// Main Function
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;
}
// Main function
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP