如何有效地查找数组中的重复元素?我的意思是说迭代次数非常少 [英] How to find duplicate elements in array in effective way? I mean to say with very less iterations

查看:31
本文介绍了如何有效地查找数组中的重复元素?我的意思是说迭代次数非常少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在缺少元素的数组中找到重复的元素?如果我在缺少次数的情况下迭代数组,则性能会变慢.以有效方式迭代数组的最佳方法是什么?或者我们可以使用任何其他 Java 集合对象以更少的迭代次数或更少的时间复杂度找到重复项吗?

How to find the duplicate element in an array which is having lacks of elements? If I iterate the array for lacks of times the performance will became slow. What is the best way to iterate an array in efficient way? Or else can we use any other Java collection object to find the duplicates with less number of iterations or less time complexity?

推荐答案

您可以使用 HashSet 因为 Sets 不允许重复,只需循环元素数组并将它们插入 HashSet 使用 add() 方法.如果 add() 方法返回 false 则该元素已存在于集合中,并且它在那里供您复制.这样你只循环一次数组,导致 O(n) 的时间和空间复杂度.

You can use a HashSet because Sets don't allow duplicates, just loop over array of elements and insert them into a HashSet using the add() method. If the add() method returns back false then that element already exists in the set and it is there for your duplicate. This way you only loop over the array once which results in a time and space complexity of O(n).

这篇关于如何有效地查找数组中的重复元素?我的意思是说迭代次数非常少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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