在程式中,我形成了一個如下所示的陣列:
unsigned short types[] = {1,1,2,3,4,100,7,8,1,1};
我需要查找并輸出陣列中出現的唯一值的數量。對于此示例,唯一值是:1、2、3、4、100、7、8,其中只有 7 個。也就是說,程式應該顯示:
total number of unique values in the given array - 7.
陣列中可能值的范圍是 0-0xFF (0 - 255)。陣列的大小types是65535。陣列可以修改,可以用它做任何事情來得到答案,但希望計算的復雜性不是很大。如何在 C 中做到這一點?
uj5u.com熱心網友回復:
在@wohlstad對該問題的評論之后,以下函式將陣列及其大小作為引數,并列印答案:
編輯:添加了一個 main 以顯示使用示例并更改了回傳,以便它可以更輕松地處理錯誤,以防用戶提出問題時不清楚。
#include <stdio.h>
int print_unique_values_in_array(unsigned short* array, int len) {
if (len <= 0 || array == NULL) {
// error message
return -1;
}
int occurrences[256] = {0}; // initialize all values to 0.
for (int i=0; i < len; i ) {
if (array[i] > 255 || array[i] < 0) {
// error message
return -1;
}
occurrences[array[i]] = 1;
}
int unique_occurrences = 0;
for (int i=0; i < 256; i ) {
if (occurrences[i] == 1)
unique_occurrences = 1;
}
printf("total number of unique values in the given array - %d\n", unique_occurrences);
return unique_occurrences;
}
int main() {
unsigned short types[10] = {1,1,2,3,4,100,7,8,1,1};
int size = 10;
int unique_occurrences = print_unique_values_in_array(types, size);
if (unique_occurrences < 0) {
// ...
return 1;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466271.html
