在数组中搜索重复值 [英] Searching for duplicate values in an array

查看:59
本文介绍了在数组中搜索重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C还是很陌生,希望有一些指导。我试图输入一个数组的7个整数并搜索它们,以查看是否有任何数字仅出现一次。这是我到目前为止的内容:

I am very new to C and I am hoping for some pointers. I am attempting to take an input of 7 integers of an array and search through them to see if any number appears only once. Here is what I have so far:

#define size 7
int main(void)
{
int array[size], target, i, prev, count;
//Initialize the array
printf("Please enter %d integers", size);
scanf("%d", &target);
prev = array[0];
count = 1;

for(i = 0; i<size; i++)
{
scanf("%d", &array[i]);
...

我意识到这很糟糕,但是C对我来说却完全陌生。我已经弄清楚了如何从用户那里输入7个整数,但是我没有第一个线索来开始尝试对它们进行索引。我还意识到,有更先进的方法可以解决这个问题。但是,我正在尝试使用业余人员可以理解的基本概念找到解决方案。

I realize it is quite terrible but C is completely strange to me. I figured out how to input the 7 integers from the user but I haven't the first clue as to where to start attempting to index them. I also realized that there are more advanced ways to figure it out; however, I am attempting find the solution using basic concepts that an amateur could understand.

推荐答案

这可以在O(n ^ 2)算法:

This can be done in O(n^2) algorithm:

int yes = 1, i, j;
for (i = 0; i < n; ++i)
{
   for (j = i + 1; j < n; ++j) if (arr[i] == arr[j])
   {
       printf("Found a duplicate of %d\n", arr[i]);
       yes = 0;
       break;
   }
   if (!yes) break;
}
if (yes) printf("No duplicates");

这篇关于在数组中搜索重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆