【发布时间】:2020-08-13 01:52:37
【问题描述】:
C 函数。 这是我的工作代码。当给定一个随机数组大小时,它会显示此输出;
输入数组的大小:20
数组中有什么:
3 6 17 15 13 15 6 12 9 1 2 7 10 19 3 6 0 6 12 16
3 出现 2 次。
6 出现 4 次。
15 出现 2 次。
6 出现 3 次。
12 出现 2 次。
6 出现 2 次。
但是我想知道一旦搜索了某个数字以不重复循环,您将如何实施?
#include <stdio.h>
#include <stdlib.h>
/* shows duplicate numbers in randomly generated array*/
void display_repeats(int *a, int n){
int i, j;
int count = 0;
for(i = 0; i < n; i++){
for(j = i; j < n; j++){
if(a[i] == a[j]){
count++;
}
}
if(count > 1){
printf("%3d occurs %3d times.", a[i], count);
printf("\n");
}
count = 0;
}
}
int main(void){
int array_size = 0;
int *my_array;
int i = 0;
printf("Enter the size of the array: ");
scanf("%d", &array_size);
/*initialises the array to the appropriate size */
my_array = malloc(array_size * sizeof my_array[0]);
if(NULL == my_array){
fprintf(stderr, "memory allocation failed!\n");
return EXIT_FAILURE;
}
for(i = 0; i < array_size; i++){
my_array[i] = rand() % array_size;
}
printf("What's in the array:\n");
for(i = 0; i < array_size; i++){
printf("%d ", my_array[I]);
}
printf("\n");
display_repeats(my_array, array_size);
/* release the memory associated with the array */
free(my_array);
return EXIT_SUCCESS;
}
【问题讨论】:
-
欢迎来到 SO!保留另一个数组
seen来跟踪您已经处理过的每个元素怎么样?如果您尚未处理该号码,请对其进行处理并将其添加到seen。如果它在seen中,请不要重新处理它。另一个想法:对数组进行排序并计算运行次数。 -
如果存储在数组中的数字范围很小(例如,数组包含从 0 到 1000 的数字),那么您可以在 O(n) 时间内使用单个循环执行此操作计数排序。我举个例子。
-
这是一个示例:onlinegdb.com/rk2ADXMMv 我将范围设置为 -20 到 20,但您可以将其更改为任何值 - 您甚至可以再添加一个循环来确定这些值。
-
这里是一个计算范围的例子:onlinegdb.com/SkML5mGMD
-
发布的代码缺少
rand()函数的初始化。建议:#include <time.h>和srand( (unsigned)time( NULL ) );