最普通最容易想到的方法是2次循环,代码如下:
public static boolean containsDuplicate(int[] nums) {
for(int n=0;n<nums.length-1;n++){
for(int m=n+1;m<nums.length;m++){
if(nums[n]==nums[m]){
return true;
}
}
}
return false;
}缺点:过于暴力,执行效率低,如果数组特别庞大,运行时间过长。在leetcode上看到一个效率很高的方法,用了Hashset,代码如下:
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i : nums)
if(!set.add(i))// if there is same
return true;
return false;
}关键字:hashset
本文介绍了一种利用HashSet提高数组查找重复元素效率的方法,对比传统的双重循环,显著提升了执行速度。通过实例演示了如何使用HashSet进行优化,并解释了其原理。

被折叠的 条评论
为什么被折叠?



