问题描述
我有一个分配创建一个算法来找到重复在一个数组,其中包括数值。但它并没有说哪一种,整数或浮点数。我写了下面的伪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
这篇关于算法查找重复在一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!