算法查找重复在一个数组 [英] Algorithm to find duplicate in an array

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

问题描述

我有一个分配创建一个算法来找到重复在一个数组,其中包括数值。但它并没有说哪一种,整数或浮点数。我写了下面的伪code:

I have an assignment to create an algorithm to find duplicates in an array which includes number values. but it has not said which kind of numbers, integers or floats. I have written the following pseudocode:

 FindingDuplicateAlgorithm(A) // A is the array
      mergeSort(A);
      for  int i <- 0 to i<A.length
           if A[i] == A[i+1]
                 i++
               return  A[i]
           else
                 i++

有我创建了一个有效的算法? 我觉得这是我的算法有问题,它返回重复号码的几个时间。例如,如果阵列包括2在两个用于两个索引我将不得不... 2,2,...在输出中。我能怎样改变来回报每duplicat只有一次? 我认为这是一个好的算法为整数,但它的工作原理很好的浮点数呢?

have I created an efficient algorithm? I think there is a problem in my algorithm, it returns duplicate numbers several time. for example if array include 2 in two for two indexes i will have ...2, 2,... in the output. how can i change it to return each duplicat only one time? I think it is a good algorithm for integers, but does it work good for float numbers too?

推荐答案

要处理的重复,你可以做到以下几点:

To handle duplicates, you can do the following:

if A[i] == A[i+1]:
    result.append(A[i]) # collect found duplicates in a list
    while A[i] == A[i+1]: # skip the entire range of duplicates 
        i++               # until a new value is found

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

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