gpt4 book ai didi

在数组中查找重复项的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:29:12 31 4
gpt4 key购买 nike

我有一项任务是创建一个算法来查找包含数值的数组中的重复项。但它没有说是哪种数字、整数或 float 。我写了以下伪代码:

 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、...。我如何更改它以仅返回每个副本一次?我认为这是一个很好的整数算法,但它也适用于 float 吗?

最佳答案

要处理重复项,您可以执行以下操作:

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

关于在数组中查找重复项的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4192724/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com