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